I\'m building navigation for a site and for the life of me I can\'t figure out recursion. I have all my data stored via MySQL using this design:
Here's an example with recursion.
function buildNavigation($items, $parent = NULL)
{
$hasChildren = false;
$outputHtml = '%s
';
$childrenHtml = '';
foreach($items as $item)
{
if ($item['parent'] == $parent) {
$hasChildren = true;
$childrenHtml .= '- '.$item['category_name'];
$childrenHtml .= buildNavigation($items, $item['category_id']);
$childrenHtml .= '
';
}
}
// Without children, we do not need the tag.
if (!$hasChildren) {
$outputHtml = '';
}
// Returns the HTML
return sprintf($outputHtml, $childrenHtml);
}
print buildNavigation($items);
That script produces the following output :
- Menu 1
- Menu 2
- Sub Menu 2.1
- Sub Menu 2.2
- Sub Menu 2.3
- Sub Menu 2.2.1
- Sub Menu 2.2.2
- Sub Menu 2.2.3
- Menu 3