Skip to content

Instantly share code, notes, and snippets.

@enapupe
Last active December 23, 2015 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enapupe/6641766 to your computer and use it in GitHub Desktop.
Save enapupe/6641766 to your computer and use it in GitHub Desktop.
<?php
function get_menu_html($items, $root_id = 0) {
$html = array();
foreach ($items as $item)
$children[$item['parent_id']][] = $item;
// loop will be false if the root has no children (i.e., an empty menu!)
$loop = !empty($children[$root_id]);
// initializing $parent as the root
$parent = $root_id;
$parent_stack = array();
// HTML wrapper for the menu (open)
$html[] = '<ul>';
while ($loop && ( ( $option = each($children[$parent]) ) || ( $parent > $root_id ) )) {
if ($option === false) {
$parent = array_pop($parent_stack);
// HTML for menu item containing childrens (close)
$html[] = str_repeat("\t", ( count($parent_stack) + 1 ) * 2) . '</ul>';
$html[] = str_repeat("\t", ( count($parent_stack) + 1 ) * 2 - 1) . '</li>';
} elseif (!empty($children[$option['value']['id']])) {
$tab = str_repeat("\t", ( count($parent_stack) + 1 ) * 2 - 1);
// HTML for menu item containing childrens (open)
$html[] = sprintf(
'%1$s<li><a href="%2$s">%3$s</a>', $tab, // %1$s = tabulation
$option['value']['href'], // %2$s = link (URL)
$option['value']['title'] // %3$s = title
);
$html[] = $tab . "\t" . '<ul class="submenu">';
array_push($parent_stack, $option['value']['parent_id']);
$parent = $option['value']['id'];
}
else
// HTML for menu item with no children (aka "leaf")
$html[] = sprintf(
'%1$s<li><a href="%2$s">%3$s</a></li>', str_repeat("\t", ( count($parent_stack) + 1 ) * 2 - 1), // %1$s = tabulation
$option['value']['href'], // %2$s = link (URL)
$option['value']['title'] // %3$s = title
);
}
// HTML wrapper for the menu (close)
$html[] = '</ul>';
return implode("\n", $html);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment