我创建了一个MySQL数据库表,我希望根据父数据库显示菜单结构。菜单表包含以下数据:
id | menuname | parentid
---+-------------------+---------
1 | dashboard | 0
2 | Content | 0
3 | Home Page Content | 2
4 | Banners | 2
5 | Settings | 0
6 | Block Content | 3
7 | Site Content | 3
这样菜单结构将如下所示:
我已经通过这里的帖子Recursive menu tree from array了 但是,无法理解基础知识。但是,我明白我需要编写一个递归函数来解决这个问题。有人可以给我一些如何生成上述内容的想法吗?
答案 0 :(得分:0)
想象一下,您是从带有SQL查询的数据库中选择的
SELECT * FROM my_table ORDER BY parentid ASC, id ASC
你在PHP中有这个数组
$arr = [
[
"id"=>1,
"username"=>"dashboard",
"parentid"=>0
],
[
"id"=>2,
"username"=>"dashboard",
"parentid"=>0
],
[
"id"=>5,
"username"=>"dashboard",
"parentid"=>0
],
[
"id"=>3,
"username"=>"dashboard",
"parentid"=>2
],
[
"id"=>4,
"username"=>"dashboard",
"parentid"=>2
],
[
"id"=>6,
"username"=>"dashboard",
"parentid"=>3
],
[
"id"=>7,
"username"=>"dashboard",
"parentid"=>3
],
];
$categories = [];
foreach ($arr as $item){
if($item["parentid"]==0){
$categories[$item["id"]] = $item;
}else{
$categories[$item["parentid"]]["subs"][] = $item;
}
}