Build a tree menu with li tag from array

前端 未结 2 1683
闹比i
闹比i 2021-01-26 10:46

I am retrieving an array and I made function to structure the array so it looks tree array. How to make tree menu with list tag (ul, li)

function buildTree(array         


        
相关标签:
2条回答
  • 2021-01-26 11:08
    //build Tree structure from array
    function buildTree(array &$elements, $parentId = 0, $elkey = null) {
        $branch = array();
    
        foreach ($elements as $key=>$element) {
            if ($element[$elkey]['parent_id'] == $parentId) {
                $children = buildTree($elements, $element[$elkey]['id'], $elkey);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[$element[$elkey]['id']] = $element;
                unset($elements[$key]);
            }
        }
        return $branch;
    }
    //Build Menu       
    function buildMenu($arr, $elmkey) {
        echo "<ul>";
        foreach ($arr as $val) {
                if (!empty($val['children'])) {
                        echo "<li>" . $val[$elmkey]['title'];
                        menu($val['children'], $elmkey);
                        echo "</li>";
                } else {
                        echo "<li>" . $val[$elmkey]['title'] . "</li>";
                }
        }
        echo "</ul>";
    }
    
    $menuTree = buildTree($systemPageCategories, 0, 'SystemPageCategory');
    echo menu($menuTree, 'SystemPageCategory'); 
    

    buildMenu() Reference

    0 讨论(0)
  • 2021-01-26 11:11

    Try this example, pass $menuTree variable to buildMenu function.

        function buildMenu($menus)
        {
        $data = '';
        foreach ($menus as $key => $menu) {
            if ($key == 'children' && !empty($menu)) {
                $data .= buildMenu($menu);
                continue;
            }
    
            $data .= '<li><a href="'.$menu['url'].'">'.$menu['title'].'</a></li>';
        }
    
        if (!empty($data)) {
            $data .= '<ul>'.$data.'</ul>';
        }
    
        return $data;
       }
    
    0 讨论(0)
提交回复
热议问题