-2

我想创建一个分层菜单。功能:

/*
* Table has 3 fields: `ID`, `PARENTID` and `NAME`
* `ID` is unique, `PARENTID` showing his parent node id.
* This function will go through it and build unordered list and call itself when needed to build subitems.
* $level argument used to define wich node's subitems to build. Default is 0 which is top level.
*/    
function showMenu($level = 0) {

$result = mysql_query("SELECT * FROM `menus` WHERE `submenu` = ".$level); 
echo "<ul>";
    while ($node = mysql_fetch_array($result)) { 
        echo "<li>".$node['name'];
        $hasChild = mysql_fetch_array(mysql_query("SELECT * FROM `menus` WHERE `submenu` = ".$node['id'])) != null;
        IF ($hasChild) {
            showMenu($node['id']);
        }
        echo "</li>";
    }
echo "</ul>";
}

我在一个类似问题的stackoverflow上找到了。

我有一张桌子menus

+----+----------------+---------+
| id | name           | submenu |
+----+----------------+---------+
|  1 | FIRST HEADER   |    NULL | 
|  2 | SECOND HEADER  |    NULL | 
|  3 | THIRD HEADER   |    NULL | 
|  4 | (fh) submenu 1 |       1 | 
|  5 | (fh) submenu 2 |       1 | 
|  6 | (fh) submenu 3 |       1 | 
|  7 | (sh) submenu 1 |       2 | 
|  8 | (sh) submenu 2 |       2 | 
|  9 | (th) submenu 1 |       3 | 
| 10 | item 1         |       4 | 
| 11 | item 2         |       4 | 
+----+----------------+---------+

我在脚本中使用了这个函数

showMenu(4);

结果如下:

<ul><li>item 1</li><li>item 2</li></ul> 

如您所见,甚至没有关于层次结构的消息,只有源代码中的几个项目。我的代码可能有什么问题?

4

1 回答 1

2

您只是专门要求子菜单编号4

如果您只是showMenu()不带参数调用,它将显示整个菜单树。

于 2013-01-20T01:09:45.320 回答