How can a nested array be used to create a dynamic menu in PHP?

To create a dynamic menu in PHP using a nested array, you can structure the array to represent the menu hierarchy with parent and child items. You can then use recursion to iterate over the array and generate the menu HTML dynamically based on the nested structure.

$menuItems = array(
    array(
        'label' => 'Home',
        'url' => '/home',
    ),
    array(
        'label' => 'Products',
        'url' => '/products',
        'children' => array(
            array(
                'label' => 'Category 1',
                'url' => '/products/category1',
            ),
            array(
                'label' => 'Category 2',
                'url' => '/products/category2',
            ),
        ),
    ),
);

function generateMenu($menuItems) {
    $html = '<ul>';
    foreach ($menuItems as $item) {
        $html .= '<li><a href="' . $item['url'] . '">' . $item['label'] . '</a>';
        if (isset($item['children'])) {
            $html .= generateMenu($item['children']);
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}

echo generateMenu($menuItems);