How can PHP scripts be utilized to dynamically generate navigation menus based on page hierarchy?

To dynamically generate navigation menus based on page hierarchy in PHP, you can utilize a recursive function that traverses the page structure and generates the menu items accordingly. By checking the parent-child relationships of the pages, you can create a nested menu structure that reflects the hierarchy of the pages.

function generateMenu($pages, $parent_id = 0) {
    echo '<ul>';
    foreach ($pages as $page) {
        if ($page['parent_id'] == $parent_id) {
            echo '<li><a href="' . $page['url'] . '">' . $page['title'] . '</a>';
            generateMenu($pages, $page['id']);
            echo '</li>';
        }
    }
    echo '</ul>';
}

// Example usage
$pages = [
    ['id' => 1, 'parent_id' => 0, 'title' => 'Home', 'url' => 'index.php'],
    ['id' => 2, 'parent_id' => 0, 'title' => 'About', 'url' => 'about.php'],
    ['id' => 3, 'parent_id' => 0, 'title' => 'Services', 'url' => 'services.php'],
    ['id' => 4, 'parent_id' => 3, 'title' => 'Web Development', 'url' => 'web-development.php'],
    ['id' => 5, 'parent_id' => 3, 'title' => 'Graphic Design', 'url' => 'graphic-design.php'],
];

generateMenu($pages);