How can nested menus be efficiently implemented in PHP?

Nested menus can be efficiently implemented in PHP by using recursion. This involves creating a function that iterates through the menu items and checks if each item has sub-items. If a menu item has sub-items, the function calls itself recursively to generate the nested structure. This approach allows for dynamic menus with multiple levels of nesting.

function generateMenu($menuItems) {
    $output = '<ul>';
    
    foreach ($menuItems as $item) {
        $output .= '<li>' . $item['label'];
        
        if (!empty($item['children'])) {
            $output .= generateMenu($item['children']);
        }
        
        $output .= '</li>';
    }
    
    $output .= '</ul>';
    
    return $output;
}

$menu = [
    ['label' => 'Home'],
    ['label' => 'About', 'children' => [
        ['label' => 'Team'],
        ['label' => 'History']
    ]],
    ['label' => 'Services', 'children' => [
        ['label' => 'Web Development'],
        ['label' => 'Graphic Design']
    ]]
];

echo generateMenu($menu);