Want you want is a recursive method that calls itself as it loops through the nested tree.
Here is an example... notice what happens is we set the children to an array, if there are children the function calls itself, and it will keep calling itself as long as it keeps finding children.
//BUILD THE TREE
$tree = array();
//GET TOP LEVEL ITEMS
$top_level = select id, name from menu where parent = 0;
foreach($top_level as $top){
$branch = array();
$branch['id'] = $top->id;
$branch['name'] = $top->name;
$children = select id, name from menu where parent = $top->id;
//CHECK FOR CHILDREN
if(count($children > 0)) {
//THERE ARE CHILDREN PASS THEM TO A RECURSIVE FUNCTION TO GET LIST
$branch['children'] = getChildren($children)
else {
//THERE ARE NO CHILDREN SET TO EMPTY ARRAY
$branch['children'] = array();
}
$tree[] = $branch;
}
function getChildren($children) {
foreach($children as $child){
$child_branch = array();
$child_branch['id'] = $child->id;
$child_branch['name'] = $child->name;
$children = select id, name from menu where parent = $child->id;
//CHECK FOR CHILDREN
if(count($children > 0)) {
//THERE ARE CHILDREN PASS THEM TO THIS FUNCTION (RECURSION) TO GET LIST
$child_branch['children'] = getChildren($children)
else {
//THERE ARE NO CHILDREN SET TO EMPTY ARRAY
$child_branch['children'] = array();
}
return $child_branch;
}
}
You can also create a recursive method to traverse the tree and display the potentially unlimited nested items.
Yeah, that is how I solved it for the moment but I thought there might be a way to retrieve the menu tree from the database without the need of further processing. Seems like I need to stick with that solution.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community