How can a nested list be created in PHP using data from a database?

To create a nested list in PHP using data from a database, you can fetch the data from the database and organize it into a nested array structure. Then, you can iterate through the nested array to generate the nested list in HTML format. This can be achieved by using a recursive function to handle the nested structure of the data.

<?php
// Fetch data from the database
$data = [
    ['id' => 1, 'name' => 'Parent 1', 'parent_id' => null],
    ['id' => 2, 'name' => 'Child 1-1', 'parent_id' => 1],
    ['id' => 3, 'name' => 'Child 1-2', 'parent_id' => 1],
    ['id' => 4, 'name' => 'Parent 2', 'parent_id' => null],
    ['id' => 5, 'name' => 'Child 2-1', 'parent_id' => 4]
];

// Organize data into a nested array structure
$nestedData = [];
foreach ($data as $item) {
    $nestedData[$item['parent_id']][] = $item;
}

// Recursive function to generate nested list
function generateNestedList($items, $parentId = null) {
    if (isset($items[$parentId])) {
        echo '<ul>';
        foreach ($items[$parentId] as $item) {
            echo '<li>' . $item['name'];
            generateNestedList($items, $item['id']);
            echo '</li>';
        }
        echo '</ul>';
    }
}

// Generate the nested list
generateNestedList($nestedData);
?>