PHP: Recursively get children of parent
- by Nic Hubbard
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.