如何使用PHP从MySQL创建嵌套菜单? [英] How to create a nested menu from MySQL with PHP?
问题描述
我需要使用MySQL数据库中的PHP创建菜单.
I need to create a menu with PHP from a MySQL database.
称为类别的表具有ID,名称,parent_id,shortdesc等.
Table called categories has id, name, parent_id, shortdesc, etc.
输出需要在partent列表下具有父级列表和子级列表,如下所示.
The output need to have parent list and children list under the partent list as follows.
如果您可以向我显示代码或网站,我将不胜感激.
If you can show me codes or website, I will appreciate it.
<ul id="catmenu">
<li class="menulist">Cars
<ul>
<li>Ford</li>
<li>Honda</li>
<li>Toyota</li>
</ul>
</li>
<li class="menulist">Food
<ul>
<li>Pasta</li>
<li>Pizza</li>
...
</ul>
</li>
...
...
</ul>
推荐答案
这是专门针对两个层次的.推荐的方法更多的是使用经过优化的表结构进行遍历,例如 http ://articles.sitepoint.com/article/hierarchical-data-database/2 (在其他地方指出),或者提取所需的数据并将其放入字典(关联数组)中并以这种方式查询.
This is specifically for two levels deep. Recommended approach should it be more is to use an optimized table structure for traversal, like http://articles.sitepoint.com/article/hierarchical-data-database/2 (pointed out elsewhere) or to pull the data you need and push it into a dictionary (associative array) and query it that way.
<?php
$query = <<<EOT
SELECT
parent.name as parent_name,
child.name as child_name,
FROM
items child
INNER JOIN
items parent
ON
child.parent_id = parent.id
ORDER BY
parent.name
EOT;
$result = mysql_query($query) or die('Failure!');
echo "<ul id=\"catmenu\">";
$last_parent = '';
while($row = mysql_fetch_array($result)){
// If this is a new category, start a new one
if($last_parent != $row['parent_name']){
// Unless this is the first item, close the last category
if($last_parent != ''){
echo "</ul></li>";
}
$last_parent = $row['parent_name'];
echo "<li class=\"menulist\">{$row['parent_name']}<ul>";
}
echo "<li>{$row['child_name']}</li>";
}
// If we actually had items, close the "category"
if($last_parent != ''){
echo "</ul></li>";
}
echo "</ul>";
?>
这篇关于如何使用PHP从MySQL创建嵌套菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!