How can PHP be used to ensure that all levels of a dynamic menu are displayed correctly, especially when clicking on a link?
When clicking on a link in a dynamic menu, PHP can be used to ensure that all levels of the menu are displayed correctly by using recursive functions to iterate through the menu items and their children. This way, all levels of the menu can be displayed without missing any submenus.
function displayMenu($menuItems, $parentId = 0) {
echo '<ul>';
foreach ($menuItems as $menuItem) {
if ($menuItem['parent_id'] == $parentId) {
echo '<li>' . $menuItem['name'];
$children = getChildren($menuItems, $menuItem['id']);
if (!empty($children)) {
displayMenu($menuItems, $menuItem['id']);
}
echo '</li>';
}
}
echo '</ul>';
}
function getChildren($menuItems, $parentId) {
$children = array();
foreach ($menuItems as $menuItem) {
if ($menuItem['parent_id'] == $parentId) {
$children[] = $menuItem;
}
}
return $children;
}
// Usage example
$menuItems = [
['id' => 1, 'name' => 'Home', 'parent_id' => 0],
['id' => 2, 'name' => 'About', 'parent_id' => 0],
['id' => 3, 'name' => 'Services', 'parent_id' => 0],
['id' => 4, 'name' => 'Contact', 'parent_id' => 0],
['id' => 5, 'name' => 'Our Team', 'parent_id' => 2],
['id' => 6, 'name' => 'Mission', 'parent_id' => 2],
['id' => 7, 'name' => 'Vision', 'parent_id' => 2],
];
displayMenu($menuItems);