我有一个多维数组,可用于构建导航菜单。它可以包含任意数量的子菜单(或子菜单)。菜单工作正常。当有人单击菜单链接时,将打开ID为“ menuid”的产品类别。但是,我还需要知道当前menuid的所有子项的menuid(但不是孙子级,等等)。
这是数组的示例:
Array
(
[0] => Array
(
[menutype] => url
[menuid] => 46
)
[1] => Array
(
[menutype] => product_category
[menuid] => 55
[children] => Array
(
[0] => Array
(
[menutype] => product_category
[menuid] => 69
[children] => Array
(
[0] => Array
(
[menutype] => product_category
[menuid] => 211
)
[1] => Array
(
[menutype] => product_category
[menuid] => 57
)
[2] => Array
(
[menutype] => product_category
[menuid] => 166
)
)
)
[1] => Array
(
[menutype] => product_category
[menuid] => 57
)
[2] => Array
(
[menutype] => product_category
[menuid] => 94
)
)
)
[2] => Array
(
[menutype] => posts_category
[menuid] => 45
)
)
例如,我想知道如何为菜单ID为69的元素获取子元素中元素的 menuid 值。(应返回包含211的数组,57和166)。
答案 0 :(得分:1)
您可以使用如下递归函数来完成此操作:
function getChildIds($menuItems, $parentId) {
foreach ($menuItems as $menuItem) {
if (isset($menuItem['children'])) {
$result = getChildIds($menuItem['children'], $parentId);
if ($result !== false) {
return $result;
}
}
if ($menuItem['menuid'] == $parentId) {
$result = [];
if (isset($menuItem['children'])) {
foreach ($menuItem['children'] as $childItem) {
$result[] = $childItem['menuid'];
}
}
return $result;
}
}
return false;
}
请注意,如果找到menuid但没有子级,则返回一个空数组;如果找不到id,则返回false。
答案 1 :(得分:0)
您还可以通过以下更有效的方式使用递归函数:
$menu = [
[
'menutype' => 'url',
'menuid' => 46,
],
[
'menutype' => 'product_category',
'menuid' => 55,
'children' => [
[
'menutype' => 'product_category',
'menuid' => 69,
'children' => [
[
'menutype' => 'product_category',
'menuid' => 211
],
[
'menutype' => 'product_category',
'menuid' => 57
],
[
'menutype' => 'product_category',
'menuid' => 166
]
]
],
[
'menutype' => 'product_category',
'menuid' => 57
],
[
'menutype' => 'product_category',
'menuid' => 94
]
]
],
[
'menutype' => 'posts_category',
'menuid' => 45
]
];
function getMenu(array $menu, $menuId, $children = true)
{
foreach ($menu as $menuItem) {
if (array_key_exists('menuid', $menuItem) && $menuItem['menuid'] == $menuId) {
if ($children === true && array_key_exists('children', $menuItem)){
return $menuItem['children'];
}
return $menuItem;
}
if (array_key_exists('children', $menuItem)) {
return getMenu($menuItem['children'], $menuId, $children);
}
}
}
getMenu($menu, 69);