带有 PHP/MySQL 的分层递归菜单 [英] Hierarchical recursion menu with PHP/MySQL
问题描述
对于你们中的一些人来说,这应该(希望如此)是一个很容易回答的问题.
This should (hopefully) be a pretty easy question for some of you to answer.
我有一个来自 mySQL 数据库的有效递归菜单,现在我的主要问题是:
I have a working Recursive menu from a mySQL database, now my main problem is:
创建 URL 的最佳方法是什么?我更喜欢把每一行的标题带进来,比如/eggs/milk/bacon/.鸡蛋为 0 级,例如:鸡蛋 0、牛奶 1、培根 2.关于如何动态输出这个的任何想法?
What is the best way to create the URL? I would prefer to bring in the title of each row like /eggs/milk/bacon/. Eggs being level 0 like: eggs-0, milk-1, bacon-2. Any ideas on how to dynamicly output this?
我非常喜欢cletus"所说的关于这个问题的一些评论:PHP/MySQL - 构建导航菜单层次结构
I am pretty much going for what "cletus" said a few comments down on this question: PHP/MySQL - building a nav menu hierarchy
但我需要更多关于如何去做的解释.
But I need a bit more explanation on how to do it.
推荐答案
除非您打算经常修改菜单树,否则为每个菜单项预先存储所需的分层 URL 可能是最简单的(对于运行时分辨率为).
Unless you plan to modify your menu tree often, pre-storing the required hierarchical URL for each menu item is probably the easiest (for run-time resolution that is).
如果您希望经常修改树,比如说 - 通过网络界面,那么每次阅读菜单时都可以更轻松地生成路径,如下所示:
If you expect the tree to be modified often enough, lets say - through a web interface, then it would be easier to generate the paths every time you read the menu, something like this:
id | name | parent
----+--------+-------
0 | eggs | NULL
1 | milk | 0
2 | bacon | 1
3 | tomato | 0
4 | lettuce| 1
foreach (query("SELECT * FROM menu ORDER BY parent ASC") as $row) {
$menuitem = array_merge(array(), $row);
$menuLookup[$menuitem['id']] &= $menuitem;
if ($menuitem['parent'] == null) {
$menuitem['path'] = "/" . $menuitem['name'];
$menu[] &= $menuitem[];
} else {
$parent &= $menuLookup[$menuitem['parent']];
$menuitem['path'] = $parent['path'] . "/" . $menuitem['name'];
$parent['menu'][] &= $menuitem;
}
}
我没有调试这段代码,只是测试了它的正确性;-)
I haven't debugged this code, only tested it for correctness ;-)
这篇关于带有 PHP/MySQL 的分层递归菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!