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);
?>
Related Questions
- Is it advisable to seek help from the official PHPKIT forum when encountering login issues?
- What is the correct syntax for displaying content within a textarea element in PHP?
- What are the limitations of MongoDB in terms of handling complex queries and relationships compared to traditional SQL databases, as highlighted in the thread?