PHP 动态下拉菜单
情况是这样的: 我有一个需要从数据库动态创建的菜单。 菜单层次结构由表中的“父”列确定(每个条目都有一个父项,如果它只是父项,则为 NULL)
问题是,考虑到我需要正确的,我无法想到如何动态地执行此操作我的下拉菜单的
结构。 这要求我在父页面的 foreach 中拥有子页面的“foreach”? 如果有道理的话,有解决办法吗?
仅供参考:我正在使用的数组返回:
array(31) {
[0]=> array(5)
{ ["id"]=> string(2) "31" ["title"]=> string(4) "Home" ["linkable"]=> string(1) "1" ["parent"]=> NULL ["override"]=> string(1) " " }
[1]=> array(5)
{ ["id"]=> string(2) "30" ["title"]=> string(11) "Shop Online" ["linkable"]=> string(1) "1" ["parent"]=> string(2) "31" ["override"]=> string(4) "shop" }
and on and on.
Here's the situation:
I have a menu that needs to be created dynamically from the database.
The menu hierarchy is determined by a 'parent' column in the table (each entry has one parent or NULL if it is only a parent)
The problem is that I can't think of how I would dynamically do this, considering I need proper <ul><li><ul><li>
structure for my drop-down menu.
This requires that I have my 'foreach' of child pages, within the foreach of parent pages?
If that makes sense, is there a solution?
FYI: The array I am working with returns:
array(31) {
[0]=> array(5)
{ ["id"]=> string(2) "31" ["title"]=> string(4) "Home" ["linkable"]=> string(1) "1" ["parent"]=> NULL ["override"]=> string(1) " " }
[1]=> array(5)
{ ["id"]=> string(2) "30" ["title"]=> string(11) "Shop Online" ["linkable"]=> string(1) "1" ["parent"]=> string(2) "31" ["override"]=> string(4) "shop" }
and on and on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要编写一个递归函数来执行此操作并让它调用自身。我还没有对此进行测试,但我认为它应该可以帮助您开始。我不会认可这个函数的效率,因为它会遍历数组中的每个项目并进行比较,即使您每次运行只需要一个或两个项目(可能)。
PHP:
然后将其输出到您的页面上。类似于:
这是我的示例数组:
You need to write a recursive function to do this and have it call itself. I haven't tested this out, but I think it should get you started. I wouldn't endorse this function's efficiency since it runs through every item in the array and does a comparison even though you're going to only need an item or two from each run (likely).
PHP:
Then output this on your page. Something like:
Here is my sample array:
无需递归。
现在,属于父级的所有链接都列在以父级命名的数组中。您的其他链接位于单独的数组中。如果你愿意的话,你可以加入他们。
根据您的应用程序的需要对其进行扩展。
No recursion necessary.
Now you have all of your links that belong to a parent listed in an array named after the parent. Your other links are in a separate array. You can join them if you like.
Extend it as is required for your application.