嵌套的ul li导航

时间:2014-02-02 15:26:31

标签: php

所以结果应该是这样的:

<ul>
    <li><a href="url">Item 1</a></li>
    <li><a href="url">Item 2</a>
        <ul>
            <li><a href="url">Subitem 1</a></li>
            <li><a href="url">Subitem 2</a></li>
        </ul>
    </li>
    <li><a href="url">Item 3</a></li>
</ul>

MySQL数据库:

id | value     | url | parent
---+-----------+-----+-------
1  | Item 1    | 1   | 0
2  | Item 2    | 2   | 0
3  | Subitem 3 | 3   | 2
4  | Subitem 4 | 4   | 2
5  | Item 5    | 5   | 0

该网址来自另一个MySQL表:

id | url
---+----
1  | url
2  | url
3  | url
4  | url
5  | url

谢谢

1 个答案:

答案 0 :(得分:0)

首先获取没有父级的行(其中parent = 0)并循环它们

foreach($parents as $row) {
echo '<li><a href="url">Item 2</a>';

//here get the items whose parent is $row['parent']
if(count($childs)>0) echo '<ul>';
foreach($childs as $child_row) {
echo '<li><a href="url">Subitem 1</a></li>';
}
if(count($childs)>0) echo '</ul>';
echo '</li>';
}