Skip to content

Instantly share code, notes, and snippets.

@jackabox
Last active July 2, 2021 16:51
Show Gist options
  • Select an option

  • Save jackabox/5b6aef9fe6ccfe714b2f to your computer and use it in GitHub Desktop.

Select an option

Save jackabox/5b6aef9fe6ccfe714b2f to your computer and use it in GitHub Desktop.
Building a Navigation from an Array
<?php
// The big ass array with all the data.
$navigation = [
[
'link' => 'index.php',
'title' => 'Top Level Navigation',
'children' => [
[
'link' => 'subitem.php',
'title' => 'SubNav1',
'children' => [
[
'link' => 'subsubitem.php',
'title' => 'SubSubNav1'
]
]
]
]
],
[
'link' => 'index.php',
'title' => 'Top Level Navigation',
'children' => [
[
'link' => 'subitem.php',
'title' => 'SubNav1',
'children' => [
[
'link' => 'subsubitem.php',
'title' => 'SubSubNav1'
]
]
],
[
'link' => 'subitem.php',
'title' => 'SubNav1',
]
]
]
];
// function to build the menu
function buildNav($nav)
{
// catch the base url for the links
$home = "http://" . $_SERVER['SERVER_NAME'] . '/';
$ret = '';
$ret .= "<ul>";
// loop through each array
foreach ($nav as $value) {
// generate the link
$ret .= '<li><a href="'. $home . $value['link'] .'">'. $value['title'] .'</a></li>';
// if is children, loop again.
if (isset($value['children']) && count($value['children'])) {
$ret .= buildNav($value['children']);
}
}
$ret .= "</ul>";
return $ret;
}
echo buildNav($navigation);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment