PHP/MySQL - 构建导航菜单层次结构

2022-01-06 00:00:00 arrays hierarchy php mysql menu

所以最终菜单看起来像这样:

So the final menu will look something like this:

Item B
    Item B-1
        Item B-1-2
        Item B-1-1
Item A
    SubItem A-1
    SubItem A-2
Item C

基于以下数据库记录:

id        menu_title          parent_menu_id    menu_level    weight
1         Item A                0                           1                     1
2         Item B                0                           1                     0
3         Item C                0                           1                     2
4         SubItem A-2       1                           2                     1
5         Item B-1             2                           2                     0
6         Item B-1-1          5                           3                     1
7         SubItem A-1       1                           2                     0
8         Item B-1-2          5                           3                     0

我将如何进行显示?我的猜测是它将所有项目存储到一个多维数组中,然后以某种方式循环遍历它......

How would I go about displaying? My guess is it'll involve storing all the items into a multidimensional array, then looping through it somehow...

推荐答案

处理现有的数据结构通常会涉及递归或多个查询来构建树.

Dealing with the data structure as you have it will often involve recursion or multiple queries to build the tree.

您是否考虑过其他存储层次结构的方法?查看修改后的预购遍历 - 这是一篇不错的关于此的基于 PHP 的文章.

Have you considered other ways of storing a hierarchy? Check out modified pre-order traversal - here's a nice PHP based article about this.

相关文章