I have an array with title
and children
index.
title
is always not-null. children
is an array, empty or not-empt
I'm sure this will work :
function menu($arr) {
echo "<ul>";
foreach ($arr as $val) {
if (!empty($val['children'])) {
echo "<li>" . $val['title'];
menu($val['children']);
echo "</li>";
} else {
echo "<li>" . $val['title'] . "</li>";
}
}
echo "</ul>";
}
I had to achieve something similar, yet I wanted the HTML generation to be in inside a twig template. This could look like this:
{% macro printMenuElements(nestedListElements, level = 0, parent = 'root') %}
<ul>
{% for nestedElement in nestedListElements %}
{% set children = nestedElement.children %}
{% set title = nestedElement.title %}
{% if children is not empty and children is iterable %}
<li data-parent="{{ parent }}">
{{ title }}
{{ _self.printMenuElements(children, level +1, title) }}
</li>
{% else %}
<li data-parent="{{ parent }}">
{{ title }}
</li>
{% endif %}
{% endfor %}
</ul>
{% endmacro %}
{% block body %}
<h1>Menu</h1>
{% import _self as helper %}
{{ helper.printMenuElements(yourArray) }}
{% endblock %}
Which generates an HTML output of:
<ul>
<li data-parent="root">
N1
<ul>
<li data-parent="N1">
N11
<ul>
<li data-parent="N11">
N111
</li>
</ul>
</li>
</ul>
</li>
<li data-parent="root">
N2
<ul>
<li data-parent="N2">
N21
</li>
</ul>
</li>
</ul>
Suppose this is your array
$menu = array(
array(
'title'=>'N1',
'children'=>array(
'title'=>'N11',
'children'=>array(
'title'=>'N111',
'children'=>array(),
),
),
),
array(
'title'=>'N2',
'children'=>array(
'title'=>'N21',
'children'=>array(),
)
),
);
You could make use of recursion to build this HTML structure.
function createMenu($arr){
$str = '';
if(is_array($arr)){
$str .= "<li>".$arr['title'];
if(!empty($arr['children'])){
$str .="<ul>";
$str .= createMenu($arr['children'],$str);
$str .="</ul>";
}
$str .= "</li>";
}
return $str;
}
Now call the recursive function to create the HTML
$myMenu ='';
foreach($menu as $arr){
$myMenu .= createMenu($arr);
}
echo "<ul>".$myMenu."</ul>";
exit();