I have an array with title
and children
index.
title
is always not-null. children
is an array, empty or not-empty.
Any children
have title
and children
and so on.
$myArray = [
0 => [
'title' => 'N1',
'children' =>
[
0 =>
[
'title' => 'N11',
'children' =>
[
0 =>
[
'title' => 'N111',
'children' => [],
],
],
],
],
],
1 =>
[
'title' => 'N2',
'children' =>
[
0 =>
[
'title' => 'N21',
'children' =>
[],
],
],
],
];
Now, I want to create a drop-down menu with this array.
I have problem with creating an unordered list (ul
, li
)from this array.
I want my result to be like:
<ul>
<li>N1
<ul>
<li>N11
<ul>
<li>N111</li>
</ul>
</li>
</ul>
</li>
<li>N2
<ul>
<li>N21</li>
</ul>
</li>
</ul>
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>";
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With