I'm trying to make a bootstrap drop-down menu from an array in PHP.
I have written a recursive menu function, but I am struggling with adding the custom html attributes required for bootstrap.
My menu array is in the following format:
$menu = array(
'calendar' => array(
'text' => 'Calendar',
'rights' => 'user'
),
'customers' => array(
'text' => 'Customers',
'rights' => 'user',
'sub' => array(
'create-new' => array(
'text' => 'Create new customer',
'rights' => 'user'
),
'show-customers' => array(
'text' => 'Show all customers',
'rights' => 'user'
)
)
)
);
And the PHP to build the menu from an array as above:
function buildMenu($menu_array, $is_sub=FALSE) {
$attr = (!$is_sub) ? ' id="menu"' : ' class="submenu"';
$menu = "<ul".$attr.">";
foreach($menu_array as $id => $properties) {
foreach($properties as $key => $val) {
if(is_array($val)) {
$sub = buildMenu($val, TRUE);
}
else {
$sub = NULL;
$$key = $val;
}
}
if(!isset($url)) {
$url = $id;
}
$menu .= "<li><a href=".$url.">".$text."</a>".$sub."</li>";
unset($url, $text, $sub);
}
return $menu . "</ul>";
}
echo $output = buildMenu($menu);
My desired output is:
<ul class="nav navbar-nav">
<li><a href="#">Calendrier</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Customers <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Create new customer</a></li>
<li><a href="#">Show all customers</a></li>
</ul>
</li>
</ul>