How can a PHP script be modified to add a subcategory under an existing subcategory in a dynamic menu?
To add a subcategory under an existing subcategory in a dynamic menu using PHP, you can modify the code to include a nested array structure for the menu items. This allows for easy addition of subcategories under existing subcategories. Simply add the new subcategory as a nested array within the existing subcategory array.
$menu = [
'Category 1' => [
'Subcategory 1.1',
'Subcategory 1.2',
'Subcategory 1.3' => [
'Subcategory 1.3.1', // New subcategory added here
],
],
'Category 2' => [
'Subcategory 2.1',
'Subcategory 2.2',
],
];
// Loop through the menu array to display the menu items
foreach ($menu as $category => $subcategories) {
echo $category . '<br>';
foreach ($subcategories as $subcategory) {
if (is_array($subcategory)) {
foreach ($subcategory as $subsubcategory) {
echo '-- ' . $subsubcategory . '<br>';
}
} else {
echo '- ' . $subcategory . '<br>';
}
}
}
Related Questions
- What are common issues faced when using preg_replace to remove line breaks at the end of a string in PHP?
- How can SQL injection vulnerabilities be prevented when using $_GET variables in SQL queries in PHP?
- What are the advantages and disadvantages of generating CSS styles dynamically in PHP compared to static CSS files?