Reputation: 15
I have a multidimensional array that I use to build a navigation menu. It may consist of any number of submenus (or children). The menu works just fine. When someone clicks on a menu link, the product category with id "menuid" opens. However, I also need to know the menuid of all the children of the current menuid (but not it's grandchildren and so forth).
This is an example of the array:
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
)
)
For example, I would like to know how to get the menuid value of the elements in children for the element with menuid 69. (Should return an array with 211, 57 and 166).
Upvotes: 0
Views: 78
Reputation: 11
Also You can use recursive function with more efficient way like this:
$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);
Upvotes: 0
Reputation: 861
You can accomplish this with a recursive function like so:
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;
}
Note this will return an empty array if the menuid is found but has no children, or false if the id is not found.
Upvotes: 1