I want to print this array values as my menu with this dropdown funciton. when I am printing this array with foreach it's just printing the main array offset => value. I need to print the sub array value in services as my dropdown option.
My array is :
$menuData = [
'0' => ['Home'],
'1' => ['About'],
'2' => ['Contact'],
'3' => [
'Services' => ['Web Development', 'Wordpress', 'Mobile App'],
],
];
Here is my HTML navigation bar where I want to print the array: The sub-array named as services will print in the dropdown option and others will be printed in the main nav-item.
<ul >
<?php
foreach ($menuData as $value) { ?>
<li >
<a aria-current="page" href="#"><?php echo $value[0]; ?></a>
</li>
<?php }
?>
<li >
<a href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Services
</a>
<ul aria-labelledby="navbarDropdown">
<li><a href="#">Web Development</a></li>
<li><a href="#">Wordpress</a></li>
<li><a href="#">Mobile App</a></li>
</ul>
</li>
</ul>
CodePudding user response:
You can try something like this:
<?php
$menuData = [
'0' => ['Home'],
'1' => ['About'],
'2' => ['Contact'],
'3' => [
'Services' => [
'Web Development',
'Wordpress',
'Mobile App',
],
],
];
echo "<ul class=\"navbar-nav me-auto mb-2 mb-lg-0\">";
foreach ($menuData as $value) {
$menuItems = current($value);
$isSubArray = is_array($menuItems) || false;
if (!$isSubArray) {
echo "<li class=\"nav-item\">
<a class=\"nav-link active\" aria-current=\"page\" href=\"#\">";
echo $menuItems;
echo "</a></li>";
} else {
echo "<li class=\"nav-item dropdown\">";
echo "<a class=\"nav-link dropdown-toggle\" href=\"#\" id=\"navbarDropdown\" role=\"button\" data-bs-toggle=\"dropdown\" aria-expanded=\"false\">";
echo key($value);
echo "</a>";
echo "<ul class=\"dropdown-menu\" aria-labelledby=\"navbarDropdown\">";
foreach ($menuItems as $item) {
echo "<li><a class=\"dropdown-item\" href=\"#\">";
echo $item;
echo "</a></li>";
}
echo "</ul>";
echo "</li>";
}
}
echo "</ul>";
Hope it helps!