gpt4 book ai didi

HTML列表结构中的PHP递归菜单

转载 作者:行者123 更新时间:2023-11-28 02:15:09 26 4
gpt4 key购买 nike

这是 html 结构应该是什么样子

<li><a href="#" class="menulink">Dropdown One</a>
<ul>
<li><a href="#">Navigation Item 1</a></li>
<li>
<a href="#" class="sub">Navigation Item 2</a>
<ul>
<li class="topline"><a href="#">Navigation Item 1</a></li>
<li><a href="#">Navigation Item 2</a></li>
</ul>
</li>
<li>
<a href="#" class="sub">Navigation Item 3</a>
<ul>
<li class="topline"><a href="#">Navigation Item 1</a></li>
<li><a href="#">Navigation Item 2</a></li>
<li>
<a href="#" class="sub">Navigation Item 3</a>
<ul>
<li class="topline"><a href="#">Navigation Item 1</a></li>
<li><a href="#">Navigation Item 2</a></li>
<li><a href="#">Navigation Item 3</a></li>

</ul>
</li>
<li><a href="#">Navigation Item 4</a></li>
</ul>
</li>
<li><a href="#">Navigation Item 4</a></li>
<li><a href="#">Navigation Item 5</a></li>
</ul>
</li>
<li><a href="#" class="menulink">Dropdown Two</a>
<ul>
<li><a href="#">Navigation Item 1</a></li>
<li><a href="#">Navigation Item 2</a></li>
</ul>
</li>

这是mysql表

id |parent_id|        name     |
---+---------+-----------------+
1 | 0 |Dropdown One |
2 | 1 |Navigation Item 1|
3 | 1 |Navigation Item 2|
4 | 3 |Navigation Item 1|
5 | 3 |Navigation Item 2|
6 | 1 |Navigation Item 3|
7 | 6 |Navigation Item 1|
8 | 6 |Navigation Item 2|
9 | 6 |Navigation Item 3|
10 | 6 |Navigation Item 4|
11 | 1 |Navigation Item 4|
12 | 1 |Navigation Item 5|
13 | 0 |Dropdown Two |
14 | 13 |Navigation Item 1|
15 | 13 |Navigation Item 2|

也许不是最好的方法,但这是我的 PHP 函数尝试:

function listCategory($parent_id,$level=0) {
$query = "SELECT name, id , parent_id FROM category WHERE parent_id=".$parent_id;
$res = mysql_query($query) or die($query);
$i=1;
while (list ($name, $id) = mysql_fetch_row($res))
{
if ($level==0) {echo '<li><a href="#" class="menulink">'.$name.'</a></li>';}

echo '<li><a href="#" class="menulink">'.$name.'</a></li>';
//echo $name ." i: ".$i." level: ".$level."<br>";
$i++;
listCategory($id,$level+1);
}
}

listCategory(0);

提前感谢您的帮助

最佳答案

function listCategory($parent_id,$level=0) {
$query = "SELECT name, id , parent_id FROM category WHERE parent_id=".$parent_id;
$res = mysql_query($query) or die($query);
if(mysql_num_rows($res) == 0) return;
echo '<ul>';
while (list ($name, $id) = mysql_fetch_row($res))
{
if ($level==0)
{
echo '<li><a href="#" class="menulink">'.$name.'</a>';
}
else
{
echo '<li><a href="#">'.$name.'</a>';
}
listCategory($id,$level+1);
echo '</li>';
}
echo '</ul>';
}

关于HTML列表结构中的PHP递归菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5213309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com