我一直在做一个项目来构建一个简单的电子商务系统,在我开始显示类别导航之前一直运行良好。
当我在 MySQL 中构建类别时,我有类似的东西:
id name parent_id
1 books null
2 art 1
3 biography 1
4 games null
5 electronics null
6 FPS 4
我编写了以下 SQL 来检索父类别,然后是子类别:
SELECT parent.name AS parent_name, child1.name AS child1_name
FROM categories AS parent
LEFT OUTER JOIN categories AS child1 ON child1.parent_id = parent.id
WHERE parent.parent_id IS NULL
ORDER BY parent_name, child1_name
结果是一个包含多个数组的数组:
Array
(
[0] => Array
(
[parent_name] => Books
[child1_name] => Art
)
[1] => Array
(
[parent_name] => Books
[child1_name] => Biography
)
[2] => Array
(
[parent_name] => Clothes, Shoes & Watches
[child1_name] =>
)
[3] => Array
(
[parent_name] => Computers & Office
[child1_name] =>
)
[4] => Array
(
[parent_name] => Electronics
[child1_name] =>
)
)
我无法将此信息显示为无序列表。期望的效果是这样的:
<ul>
<li>Books
<ul>
<li>Art</li>
<li>Biography</li>
</ul>
</li>
<li>Computers</li>
<li>Electronics</li>
</ul>
有人有解决这个问题的方法吗?我是否需要更改我的 MySQL 代码甚至数据库结构?
提前致谢。