动态构建水平菜单 [英] Dynamically building horizontal menu
问题描述
我有这个JavaScript代码,它允许我创建一个带有子菜单的水平菜单,如下所示:
< ul id = 菜单 >
< li>菜单1
< ul>
< li>子菜单1< / li>
< / ul>
< / li>
< / ul>
我可以根据需要创建多个子菜单,问题是我使用PHP来抓取来自MySQL数据库的链接,不知道如何动态构建这些子菜单,而无需一次又一次手动检查子菜单。例如在MySQL表中:
字段:
Menu_ID
Menu_Name
Menu_Link
Menu_ParentID
因此,菜单ID只是一个自动增量,menu_parentid允许我为子菜单分配一个子菜单名称/链接。但为了做到这一点,我目前为此做了两个子菜单检查:
$ query =SELECT * FROM site_menu WHERE Menu_ParentID = 0;
foreach($ query AS $ q)
{
//运行结果
$ query2 =SELECT * FROM site_menu WHERE Menu_ParentID = $ q ['' ID'];
foreach($ query2 AS $ q2)
{
//运行结果
}
}
正如你所看到的,我必须查询两次才能得到第一个子菜单,如果有第三个子菜单会怎样?我必须运行3个查询吗?任何建议?
也许一个函数或do..while循环可能是为了?概念验证:
$ p $ function menuQuery($ id)
{
$ query =SELECT * FROM site_menu WHERE Menu_ParentID = $ id;
$ b $ if($ query){
foreach($ query AS $ q){
//遍历结果
menuQuery($ q-> id) ;
//顶级菜单项的初始调用
menuQuery(0);
I have this JavaScript code that allows me to create a horizontal menu with sub menus like so:
<ul id="menu">
<li>Menu 1
<ul>
<li>Sub Menu 1</li>
</ul>
</li>
</ul>
I can create as many sub menus as I want, the problem is I'm using PHP to grab the links from a MySQL database and don't know how I can dynamically build these sub menus without manually checking a sub menu over and over again. For example in the MySQL table:
Fields: Menu_ID Menu_Name Menu_Link Menu_ParentID
So menu ID is just an auto increment and the menu_parentid allows me to assign a sub menu name/link to a parent menu. But in order to do it I currently do this for 2 sub menu checks:
$query = "SELECT * FROM site_menu WHERE Menu_ParentID = 0";
foreach($query AS $q)
{
//run through the results
$query2 = "SELECT * FROM site_menu WHERE Menu_ParentID = $q['id']";
foreach($query2 AS $q2)
{
//run through the results
}
}
As you can see I have to query twice to get just the first sub menu, what if there is a third sub menu? Do I have to run 3 queries? Any suggestions?
Perhaps a function or a do..while loop may be in order? Proof of concept:
function menuQuery($id)
{
$query = "SELECT * FROM site_menu WHERE Menu_ParentID = $id";
if ($query) {
foreach($query AS $q) {
//run through the results
menuQuery($q->id);
}
}
}
//initial call of top level menu items
menuQuery(0);
这篇关于动态构建水平菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!