How can indentation be achieved for subcategories in a hierarchical category structure in PHP?
To achieve indentation for subcategories in a hierarchical category structure in PHP, you can use recursion to iterate through the categories and add appropriate indentation based on the depth of each category.
function printCategories($categories, $depth = 0) {
foreach ($categories as $category) {
echo str_repeat('&nbsp;', $depth * 4) . $category['name'] . "<br>";
if (!empty($category['subcategories'])) {
printCategories($category['subcategories'], $depth + 1);
}
}
}
// Example usage
$categories = [
['name' => 'Category 1', 'subcategories' => [
['name' => 'Subcategory 1'],
['name' => 'Subcategory 2', 'subcategories' => [
['name' => 'Sub-subcategory 1']
]]
]],
['name' => 'Category 2']
];
printCategories($categories);
Related Questions
- How can one ensure proper indentation and formatting when posting PHP code on a forum?
- Are there any best practices for managing optional parameters in PHP functions to ensure flexibility and maintainability in code?
- What are the potential pitfalls of using if statements within a foreach loop in PHP?