检索分层数据

时间:2014-04-01 11:09:34

标签: php

我正在尝试为CMS系统创建动态菜单 这是我的sql表,它有一个额外的字段叫做content

parent_id  order     id  titel                  
0          1         2   Home                   
0          2         4   Contact                
0          3         9   stuff         
2          1         1   more stuff
2          2         3   way more stuff             
9          1         10  all stuff

我想要这个结果:

home
 more stuff
 way more stuff
contact
stuff
 all stuff

这就是我调用菜单的方式:

        $resultPaginas = mysqli_query($mysqli, "select id, titel, parent_id, volgorde from TABLE order by order");
    if (!$resultPaginas) {
        die(mysqli_error($mysqli));
    }

这将显示由parent_id订购的表,订单。

它已经完成了,我知道我需要做一个while循环,但是如何执行正确的while循环来获得我想要的结果呢?

P.S。这将是一个菜单

2 个答案:

答案 0 :(得分:2)

使用此递归功能构建菜单:

function buildMenu($parentId = 0) {
    $menu = array();

    $result = mysqli_query($mysqli, "SELECT `id`, `titel`, `parent_id`, `volgorde` FROM [TABLE] WHERE `parent_id` = $parentId ORDER BY `order`");

    if ($result !== false) {
        while ($page = $result->fetch_assoc()) {
            $page["children"] = buildMenu($page["id"]);
            $menu[] = $page;
        }
    }
    return $menu;
}

像那样调用递归函数

$resultPaginas = buildMenu();

$ resultPaginas的示例内容:

Array
(
    [0] => Array
        (
            [id] => 1
            [parent_id] => 0
            [titel] => home
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [parent_id] => 1
                            [titel] => more stuff
                        )

                    [1] => Array
                        (
                            [id] => 3
                            [parent_id] => 1
                            [titel] => way more stuff
                        )

                )

        )

    [1] => Array
        (
            [id] => 4
            [parent_id] => 0
            [titel] => contact
        )

)

答案 1 :(得分:1)

首先从父ID为0的表中选择全部

并循环执行

样品:

foreach($parent as $par){
//Then you need to write another query to take all submenus for current parentid menu

  $submenus= mysqli_query($mysqli, "select id, titel, parent_id, volgorde from TABLE where parent_id = $par.id order by order");

//Then again loop trough 

foreach($submenus as $sub){

// and add existing submenus to parent menu
}
}

注意:如果语法不正确,这只是对不起。