Are there any best practices or alternative approaches that could be suggested for displaying categories and subcategories in PHP?
When displaying categories and subcategories in PHP, one approach is to use a recursive function to loop through the categories and subcategories, displaying them in a hierarchical structure. This allows for a flexible and scalable way to display nested categories.
function displayCategories($categories, $parent_id = 0, $level = 0) {
foreach ($categories as $category) {
if ($category['parent_id'] == $parent_id) {
echo str_repeat('-', $level) . $category['name'] . "<br>";
displayCategories($categories, $category['id'], $level + 1);
}
}
}
// Example usage
$categories = [
['id' => 1, 'name' => 'Category 1', 'parent_id' => 0],
['id' => 2, 'name' => 'Subcategory 1.1', 'parent_id' => 1],
['id' => 3, 'name' => 'Subcategory 1.2', 'parent_id' => 1],
['id' => 4, 'name' => 'Category 2', 'parent_id' => 0],
['id' => 5, 'name' => 'Subcategory 2.1', 'parent_id' => 4],
];
displayCategories($categories);