Lets say I have the array down here. I left out a few maps and files as this should be enough to make my point. There is no max depth to the array so there could be even more.
Array
(
[media] => Array
(
[documents] => Array
(
[0] => add.php
)
[music] => Array
(
[albums] => Array
(
[0] => add.php
)
)
[overview] => Array
(
[0] => overview.php
)
)
What I would like to get is something like the following:
<ul>
<li>Media
<ul>
<li>Documents
<ul>
<li><a href="/media/documents/add.php">Add</a></li>
</ul>
</li>
<li>Music
<ul>
<li>Albums
<ul>
<li><a href="/media/music/albums/add.php">Add</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</li>Overview
<ul>
<li><a href="/overview/overview.php">Overview</a></li>
</ul>
</li>
</ul>
I found php create navigation menu from multidimensional array dynamically but imo the accepted answer has quite a lot garbage and the result isn't quite of what I need. If you would like to know how the array is generated please let me know.
Thanks in advance for helping me
You need to use a recursive function that loops through your array. Something like this:
function outputMenu(array $array, $baseUrl = '/')
{
$html = '';
foreach ($array as $key => $item)
{
if (is_array($item))
{
$html .= '<li>'.$key.'<ul>';
$html .= outputMenu($item, $baseUrl.$key.'/');
$html .= '</ul></li>';
}
else
{
$html .= '<li><a href="'.$baseUrl.$item.'">'.ucfirst(substr($item, 0, -4)).'</a></li>';
}
}
return $html;
}
echo outputMenu($array);
$array = array(
'media'=>array('documents'=>array('add.php'),
'music'=>array('albums'=>array('add.php'))),
'overview'=>array('overview.php')
);
print_link($array);
function print_link($arre){
foreach($arre as $key => $arr){
if(is_array($arr)){
echo '<li>'. $key .'<ul>';
print_link($arr);//echo '<li>'.$arr.'</li>';
echo '</ul><li>';
} else {
echo '<li>'.$arr.'</li>';
}
}
}
you will need a function for this for this task