mysql/php 中的多级菜单

Multilevel menu in mysql/php

我正在尝试编写一个 php 代码来获取一个多级菜单,深度不受限制。我希望只用一个查询和一个循环就可以做到这一点。 这是我所拥有的: 我有一个包含以下列的 menu_items table:

id 
categories_id (overall menu id)
title (Text title)
link (Link)
ord (the order within the category itself)
parent (Parent item, which is basically another item, different from categories_id)
depth (Menu level. For whatever reason, I think it's going to help me to know the depth of every particular item)

所有菜单项都通过 categories_id 链接到特定菜单,并且所有菜单项都通过 "parent" 链接到它们的 parent 项,其中顶级项的 0 表示parent.

现在,我需要 mysql 以 return 我的整个项目列表(在同一个 categories_id 下),这样一次循环就可以将它们组织成一个漂亮的多维数组。

我该怎么做? 我想到的一种方法是,如果我可以让 MySQL 以这样一种方式订购商品,即每件商品都由所有商品进行 children.

例如: 如果我有这个结构:

Item 1
Item 2
     Item 3
     Item 4
        Item 5
     Item 6
Item 7
Item 8

其中第 1,7 和 8 项是顶级空项,第 2 项有三个 children,子项 4 child

有第 5 项

我需要 mysql 以这种方式订购上述物品: 第1项,然后第2项,然后由于第2项有children,所以应该输出第3项和第4项,因为4有child,所以应该从第5项开始,然后返回第3项6……等等……

有什么办法可以让MySQL这样订购吗?或者,我可以通过其他方式实现吗?

抱歉,如果我的问题有点令人困惑。

如果您想用一个查询加载所有内容,这是有道理的,因为菜单中很可能不会有数千个项目,那么您可以简化您的任务并使用 PHP 做更多事情而不是过于复杂SQL 查询。

因此,首先您只需使用最简单的查询加载所有内容:

$items = query('SELECT * FROM `menu_items` WHERE categories_id = ? ORDER BY `ord` asc');

这样,将所有项目划分为子菜单后,顺序将保持不变。那么你只需要一个循环来构建菜单结构。

$itemsById = [];
$children = [];
foreach ($items as $item) {
    $itemsById[$item['id']] = $item;
    $children[$item['parent']][] = $item['id'];
}

并且您可以从 $children[0] 开始递归打印它。