Support the ongoing development of Laravel.io →
Database Eloquent Architecture
Last updated 2 years ago.
0

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;
	}
}
Last updated 2 years ago.
0

You can also create a recursive method to traverse the tree and display the potentially unlimited nested items.

Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

h0kx h0kx Joined 19 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.