I am retrieving an array and I made function to structure the array so it looks tree array. How to make tree menu with list tag (ul, li)
function buildTree(array
//build Tree structure from array
function buildTree(array &$elements, $parentId = 0, $elkey = null) {
$branch = array();
foreach ($elements as $key=>$element) {
if ($element[$elkey]['parent_id'] == $parentId) {
$children = buildTree($elements, $element[$elkey]['id'], $elkey);
if ($children) {
$element['children'] = $children;
}
$branch[$element[$elkey]['id']] = $element;
unset($elements[$key]);
}
}
return $branch;
}
//Build Menu
function buildMenu($arr, $elmkey) {
echo "<ul>";
foreach ($arr as $val) {
if (!empty($val['children'])) {
echo "<li>" . $val[$elmkey]['title'];
menu($val['children'], $elmkey);
echo "</li>";
} else {
echo "<li>" . $val[$elmkey]['title'] . "</li>";
}
}
echo "</ul>";
}
$menuTree = buildTree($systemPageCategories, 0, 'SystemPageCategory');
echo menu($menuTree, 'SystemPageCategory');
buildMenu() Reference
Try this example, pass $menuTree variable to buildMenu function.
function buildMenu($menus)
{
$data = '';
foreach ($menus as $key => $menu) {
if ($key == 'children' && !empty($menu)) {
$data .= buildMenu($menu);
continue;
}
$data .= '<li><a href="'.$menu['url'].'">'.$menu['title'].'</a></li>';
}
if (!empty($data)) {
$data .= '<ul>'.$data.'</ul>';
}
return $data;
}