Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to set parent menu items active
<?php
// A very silly representation of our menu.
$menu = [
[
'title' => 'Home',
'uri' => '/',
'active' => false,
],
[
'title' => 'Category',
'uri' => '/cat',
'active' => false,
'children' => [
[
'title' => 'Subcat 1',
'uri' => '/cat/foo',
'active' => false,
],
[
'title' => 'Subcat 2',
'uri' => '/cat/bar',
'active' => false,
],
[
'title' => 'Subcat 3',
'uri' => '/cat/baz',
'active' => false,
'children' => [
[
'title' => 'Subsubcat 1',
'uri' => '/cat/baz/foo',
'active' => false,
],
],
],
],
]
];
// will go down the menu and find the active. It sets the item itself active (and returns it for good measure)
function findActiveItem($route, array &$menu, array &$parents) {
foreach ($menu as $key => &$item) {
if ($item['uri'] === $route) {
$item['active'] = true;
return $item;
}
if (isset($item['children'])) { // we have to go deeper!
$parents[] = $key; // store the key
return findActiveItem($route, $item['children'], $parents);
}
}
return false;
}
// will go through the menu and set nested items active depending on the $parents keys built by previous function
function setParentsActive(array &$menu, array $parents) {
$key = array_shift($parents);
$menu[$key]['active'] = true;
if (count($parents) > 0) { // have parents left?
setParentsActive($menu[$key]['children'], $parents);
}
}
$parents = [];
findActiveItem('/cat/baz/foo', $menu, $parents);
if (count($parents) > 0) {
setParentsActive($menu, $parents);
}
echo '<pre>';
print_r($menu);
echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment