Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP-Laravel foreach only loops once

I have a categories table with parent_id column, referring to parent category’s ID. I need to retrieve all of the ID’s that are under a certain category (all of its children & grandchildren) I wrote this recursive function but for some reason it only returns the direct children of the given category id.

What am I missing here?

function subCategoriesList($id, $data=[]){
    $children = Category::whereParentId($id)->get();
    foreach ($children as $child){
        $data[] = $child->id;
        subCategoriesList($child->id, $data);
    }
    return $data;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re not passing $data by reference, but you’re making the recursive call as if you are.

Try:

function subCategoriesList($id){
    $data=[]
    $children = Category::whereParentId($id)->get();
    foreach ($children as $child){
        $data[] = $child->id;
        $data = array_merge($data, subCategoriesList($child->id));
    }
    return $data;
}

Conversely, and for completeness, with references:

function subCategoriesList($id, &$data){
    $children = Category::whereParentId($id)->get();
    foreach ($children as $child){
        $data[] = $child->id;
        subCategoriesList($child->id, $data);
    }
}

// You must call it as follows, though
$my_data = [];
subCategoriesList($some_id, $my_data);

Personally, though, I tend to recommend that references be avoided unless there is a clear reason for them. IMO they tend to result in confusing code and side-effects, while rarely delivering the benefits that the writer thinks they are getting.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading