What is the purpose of using a recursive loop in PHP to generate a list from a database?

When generating a list from a database in PHP, using a recursive loop can be helpful when dealing with hierarchical data structures such as nested categories or menu items. This allows you to easily traverse through the data and create a nested list structure without knowing the depth of the hierarchy beforehand.

function generateList($parent_id = 0) {
    // Query the database to get all items with the given parent_id
    $items = getItemsFromDatabase($parent_id);

    if (count($items) > 0) {
        echo '<ul>';
        foreach ($items as $item) {
            echo '<li>' . $item['name'];
            generateList($item['id']); // Recursively call the function for nested items
            echo '</li>';
        }
        echo '</ul>';
    }
}

// Call the function to generate the list starting from the root level (parent_id = 0)
generateList();