我想做一个不限级别的菜单,我有一个数组
$menu = [
0 => [
'id' => 1,
'parent_id' => 0,
'title' => 'Category 1',
],
2 => [
'id' => 2
'parent_id' => 0,
'title' => 'Category 2',
],
3 => [
'id' => 3,
'parent_id' => 2,
'title' => 'Category 3',
],
4 => [
'id' => 4,
'parent_id' => 3,
'title' => 'Category 4',
]
]我想得到一个类似这样的结构:
$tree = [
0 => [
'id' => 1,
'parent_id' => 0,
'title' => 'Category 1'
],
2 => [
'id' => 2
'parent_id' => 0,
'title' => 'Category 2',
'child' => [
0 => [
'id' => 3,
'parent_id' => 2,
'title' => 'Category 3',
'child' => [
1 => [
'id' => 4,
'parent_id' => 3,
'title' => 'Category 4',
]
]
]
]
]
]我写了一些代码,但它最多工作到第二层嵌套,在第三层,问题开始出现
$tree = [];
foreach ($menu as $node) {
if (!$node['parent_id']) {
$tree[$node['id']] = $node;
}
else {
$tree[$node['parent_id']]['children'][$node['id']] = $node;
}
}
return $tree;我好像什么也没找到,也许我看起来很糟糕
发布于 2021-10-05 17:54:19
这里有一些东西可以让你开始:
function appendItem(array &$haystack, array $toAppend): void
{
foreach ($haystack as &$menuItem) {
if ($menuItem['id'] === $toAppend['parent_id']) {
if (array_key_exists('child', $menuItem)) {
$menuItem['child'][] = $toAppend;
} else {
$menuItem['child'] = [$toAppend];
}
return;
}
if (array_key_exists('child', $menuItem)) {
appendItem($menuItem['child'], $toAppend);
}
}
}
foreach ($menu as $key => $menuItem) {
if ($menuItem['parent_id'] !== 0) {
unset($menu[$key]);
appendItem($menu, $menuItem);
}
}该函数基本上遍历了一个数组,如果它找到一个元素,其中toAppend的parent_id与循环中元素的id匹配,它将被添加到该元素的子项中。如果没有,它会在它的child数组上重复这个函数(如果它存在的话)。
对此可能会做一些优化,但这是一个很好的开始。3v4l查看实际运行的代码。
https://stackoverflow.com/questions/69452475
复制相似问题