我想创建一个分层菜单。功能:
/*
* 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>
正如你所看到的,即使是一个层次结构,也没有关于源代码中的几个项目的消息。我的代码可能有什么问题?
答案 0 :(得分:2)
您具体只是请求子菜单号4
。
如果您只是在没有参数的情况下调用showMenu()
,它将显示整个菜单树。