PHP: Recursively get children of parent

Posted by Nic Hubbard on Stack Overflow See other posts from Stack Overflow or by Nic Hubbard
Published on 2010-02-28T21:12:50Z Indexed on 2010/04/20 12:13 UTC
Read the original article Hit count: 355

Filed under:
|
|
|

I have a function which gets the ids of all children of a parent from my DB. So, if I looked up id 7, it might return an array with 5, 6 and 10. What I then want to do, is recursively find the children of those returned ids, and so on, to the final depth of the children.

I have tried to write a function to do this, but I am getting confused about recursion.

function getChildren($parent_id) {
    $tree = Array();
    $tree_string;
    if (!empty($parent_id)) {
        // getOneLevel() returns a one-dimentional array of child ids
        $tree = $this->getOneLevel($parent_id);
        foreach ($tree as $key => $val) {
            $ids = $this->getChildren($val);
            array_push($tree, $ids);
            //$tree[] = $this->getChildren($val);
            $tree_string .= implode(',', $tree);
        }

        return $tree_string;
    } else {
        return $tree;
    }

}//end getChildren()

After the function is run, I would like it to return a one-dimentional array of all the child ids that were found.

© Stack Overflow or respective owner

Related posts about php

Related posts about recursion