只计算多级菜单的前两级

xtupzzrd  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(330)

我有一张table menu 带列: id , value , id_parent .
在模型中:

public function getMenu()
{
    $sql = "SELECT * FROM menu";
    return $this->db->query($sql);
}

在控制器中:

public function adminNavMenu()
{
    $this->data['menu'] = $this->model->getMenu();

    $result = [];
    foreach ($this->data['menu'] as $key => $value) {
        if ($value['id_parent'] == 0) {
            $result[$value['id']] = $value;
        } else {
            $result[$value['id_parent']]['children'][] = $value;
        }
     }
}

但它只计算多级菜单的前两级。我试图应用循环或递归,但我不能。。。
请帮帮我,纠正错误。
原始菜单视图:

Menu1
Menu2->
       Menu2-1
       Menu2-2
       Menu2-3->
                Menu2-3-1

之后的输出无效 var_dump($result) ;

Array
(
    [1] => Array
        (
            [id] => 1
            [value] => Menu1
            [id_parent] => 0
        )
    [2] => Array
        (
            [id] => 2
            [value] => Munu2
            [id_parent] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [value] => Menu2-1
                            [id_parent] => 2
                        )
                    [1] => Array
                        (
                            [id] => 4
                            [value] => Menu2-2
                            [id_parent] => 2
                        ) 
                    [2] => Array
                        (
                            [id] => 5
                            [value] => Menu2-3
                            [id_parent] => 2
                        )
                )
        )
    [5] => Array
        (
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 6
                            [value] => Menu2-3-1
                            [id_parent] => 5
                        )
                )
        )
)
i7uq4tfw

i7uq4tfw1#

从下面的代码中你可以得到一些什么想法:

<?php
function get_menu_tree($parent_id) 
{
    global $con;
    $menu = "";
    $sqlquery = " SELECT * FROM menu where id_parent='" .$parent_id . "' "; // put your query
    $res=mysqli_query($con,$sqlquery);
    while($row=mysqli_fetch_array($res,MYSQLI_ASSOC)) 
    {
           $menu .="<li>".$row['value']."</a>";

           $menu .= "<ul>".get_menu_tree($row['id'])."</ul>"; //call  recursively

           $menu .= "</li>";

    }

    return $menu;
} 
?>

调用此函数:

<?php echo get_menu_tree(0);//start from root menus having parent id 0 ?>

相关问题