I want to change structure of parent other way like Wordpress and add class if is parent.
Current Structure:
<ul>
<li>My List
<ul>
<li>Menu 1</li>
<ul>
<li>Menu 2</li>
<ul>
<li>Menu 3</li>
</ul>
<li>Menu 4</li>
</ul>
<li>Menu 5</li>
</ul>
</li>
What i want:
<ul>
<li>My List
<li>Menu 1
<ul class="sub-menu">
<li>Menu 2
<ul class="sub-menu">
<li>Menu 3</li>
</ul>
</li>
<li>Menu 4</li>
</ul>
</li>
<li>Menu 5</li>
</li>
</ul>
Code:
$lists = array(
array(
'id' => 1,
'parent' => 0,
'name' => 'Menu 1',
),
array(
'id' => 2,
'parent' => 1,
'name' => 'Menu 2',
),
array(
'id' => 3,
'parent' => 2,
'name' => 'Menu 3',
),
array(
'id' => 4,
'parent' => 1,
'name' => 'Menu 4',
),
array(
'id' => 5,
'parent' => 0,
'name' => 'Menu 5',
)
);
?>
<ul>
<li>My List
<?php
function make_list($lists, $parent = 0) {
$children = array_filter($lists, function ($v) use($parent) { return $v['parent'] == $parent; });
if(!count($children)) return;
echo "<ul>";
foreach ($children as $child) {
echo "<li>{$child['name']}</li>";
make_list($lists, $child['id']);
}
echo "</ul>";
}
make_list($lists);
?>
</li>
</ul>
You can do that with a minor change to the function to track the menu level:
Try this code, not ideal, but it works