What are the key considerations when using recursion in PHP to display nested menu items?
When using recursion in PHP to display nested menu items, it is important to consider the structure of the menu items and how they are nested. You will need to create a recursive function that can handle nested items and display them accordingly. Make sure to pass in the nested menu items as a parameter to the recursive function and handle the base case when there are no more nested items to display.
function displayMenuItems($menuItems, $indent = 0) {
foreach ($menuItems as $item) {
echo str_repeat('-', $indent) . $item['name'] . PHP_EOL;
if (isset($item['children'])) {
displayMenuItems($item['children'], $indent + 1);
}
}
}
// Example nested menu items
$menuItems = [
['name' => 'Home'],
['name' => 'About', 'children' => [
['name' => 'History'],
['name' => 'Team'],
]],
['name' => 'Services'],
];
displayMenuItems($menuItems);