Create Table : Menu : id,name,parent_id
function parseTree($menu, $root = null) {
$return = array();
# Traverse the tree and search for direct children of the root
foreach($menu as $child => $parent) {
# A direct child is found
if($parent->parent_id == $root) {
# Remove item from tree (we don't need to traverse this again)
unset($menu[$child]);
# Append the child into result array and parse its children
$return[] = array(
'name' => $parent,
'children' => $this->parseTree($menu, $child)
);
}
}
return empty($return) ? null : $return;
}
function printParent($tree){
if(!is_null($tree) && count($tree) > 0) {
echo '<ul>';
foreach($tree as $node) {
// print_r($node);exit;
echo '<li>'.$node['name']['name'];
$this->printParent($node['children']);
echo '</li>';
}
echo '</ul>';
}
}
OR=======================
public function index()
{
$allMenu = Menu::all();
$childe_parent_menu_list = array();
foreach($allMenu as $menu){
$childe_parent_menu_list[$menu->id] = $menu;
}
$menu_tree = array();
$menu_tree = $this->parseTree($childe_parent_menu_list);
$html_view = '';
$html_view = $this->printParent($menu_tree,$html_view);
return view('Menu.index',array('menus'=>$allMenu,'menu_tree'=>$html_view));
}
function parseTree($menu, $root = null) {
$return = array();
# Traverse the tree and search for direct children of the root
foreach($menu as $child => $parent) {
# A direct child is found
if($parent->parent_id == $root) {
# Remove item from tree (we don't need to traverse this again)
unset($menu[$child]);
# Append the child into result array and parse its children
$return[] = array(
'name' => $parent,
'children' => $this->parseTree($menu, $child)
);
}
}
return empty($return) ? null : $return;
}
function printParent($tree,$html_view=NULL){
$html_view = '';
if(!is_null($tree) && count($tree) > 0) {
$html_view .= '<ul>';
foreach($tree as $node) {
// print_r($node);exit;
$html_view .= '<li>'.$node['name']['name'];
$html_view .=$this->printParent($node['children'],$html_view);
$html_view .= '</li>';
}
$html_view .= '</ul>';
}
//print_r( $html_view);exit;
return $html_view;
}