PHP / MySQL 构建树形菜单
我正在尝试从我的 PHP 和 MySQL 数据库构建一个无序列表菜单树。
我有一个从数据库返回的页面对象数组。每个页面对象都有parent_id属性,如果它没有父级,则该属性设置为null。页面对象如下所示:
page object
id
title
parent_id
如果可能的话,我不想递归地执行此操作,而只访问数据库一次,因为我将在几乎每个请求上构建菜单。我想创建一个函数,我可以将对象数组传递给它,它将返回 html 列表。
I am trying to build an un-oredered list menu tree from my database in PHP and MySQL.
I have an array of page objects I am returning from the db. Each page object has parent_id attribute, which is set to null if it doesn't have a parent. Here's what the page objects look like:
page object
id
title
parent_id
If possible I would like to not do it recursively and only hit the database once, since I am going to be building the menu on almost every request. I want to create a function that I can just pass my array of objects to and it will return the html list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我喜欢 @mario 的解决方案,并通过防止多余的
对其进行了改进。我只是建议在 SQL 查询上执行 ORDER BY 以便按照您想要的顺序获取菜单(甚至可能建议将权重/序列列添加到架构中。
数据设置:
处理:
输出:
I like @mario's solution, and have improved on it with the prevention of the excess
<ul>
. I would just recommend doing anORDER BY
on your SQL query to get the menu in the order you want (might even recommend a weight/sequence column be added to the schema.Data setup:
Handling:
Output:
您可以提取所有条目并使输出函数递归,而不是递归查询数据库。它通常很简单:
将
嵌套到
中很重要。或者只使用 HTML 并省略结束
。
实际上,这会打印太多
,因此我会检查是否存在子级别并避免直接打印它。
Instead of querying the database recursively, you can just pull out all entries and make the output function recursive. It's often as trivial as:
It's only important to nest
<ul>
s into<li>
. Or just use HTML and leave out the closing</li>
.Actually this prints too many
<ul>
s, so I would check for existence of sublevels and avoid printing it directly.我最终采用了这个解决方案(pastebin 参考):
示例数据:
用法:
I ended up going with this solution (pastebin reference):
Example Data:
Usage: