How can nested navigation menus be implemented in PHP to ensure both parent and child items receive an active class?
When implementing nested navigation menus in PHP, it can be challenging to ensure that both parent and child items receive an active class when selected. One way to solve this issue is by using a recursive function to iterate through the menu items and check if the current page matches the menu item. If it does, both the parent and child items can be marked as active.
function generateMenu($menuItems, $currentPage) {
echo '<ul>';
foreach ($menuItems as $item) {
echo '<li';
if ($item['url'] == $currentPage) {
echo ' class="active"';
}
echo '>';
echo '<a href="' . $item['url'] . '">' . $item['title'] . '</a>';
if (!empty($item['children'])) {
generateMenu($item['children'], $currentPage);
}
echo '</li>';
}
echo '</ul>';
}
// Usage
$menu = [
['title' => 'Home', 'url' => 'index.php'],
['title' => 'About', 'url' => 'about.php'],
['title' => 'Services', 'url' => 'services.php', 'children' => [
['title' => 'Web Design', 'url' => 'webdesign.php'],
['title' => 'SEO', 'url' => 'seo.php'],
]],
['title' => 'Contact', 'url' => 'contact.php'],
];
$current_page = 'services.php';
generateMenu($menu, $current_page);
Related Questions
- What are the common pitfalls to avoid when transitioning from Java to PHP, particularly when working on projects like calendar displays?
- What potential security risks are associated with the use of the mail function in PHP for form submissions?
- What are the deprecated features in PHP that should be avoided when working with MySQL databases?