03/09/2014
Here is what I use for the creation of a menu with unlimited depth, which can be styled with css as you like.
Enjoy the code! If you need help or want to improve on this just let me know. I'm always open to constructive criticism.
<?php
// menu builder function, parentId 0 is the root
// Select all entries from the menu table
$result=mysql_query("SELECT ID, Naam, parent FROM Menu WHERE show_condition = 1 ORDER BY sort, parent");
// Create a multidimensional array to conatin a list of items and parents
$menu = array(
'items' => array(),
'parents' => array()
);
// Builds the array lists with data from the menu table
while ($items = mysql_fetch_assoc($result)) {
// Creates entry into items array with current menu item id ie. $menu['items'][1]
$menu['items'][$items['ID']] = $items;
// Creates entry into parents array. Parents array contains a list of all items with children
$menu['parents'][$items['parent']][] = $items['ID'];
}
// Menu builder function, parentId 0 is the root
function buildMenu($parent, $menu) {
$html = "";
if (isset($menu['parents'][$parent])) {
$html .= "<ul>\n";
foreach ($menu['parents'][$parent] as $itemId) {
if($menu['parents'][$itemId] == 0) {
$html .= "<li><a href=../".strtolower($menu['items'][$itemId]['Naam']).">".
$menu['items'][$itemId]['Naam']."</a></li>\n";
}
if(isset($menu['parents'][$itemId])) {
$html .= "<li><a href=../".strtolower($menu['items'][$itemId]['Naam']).">".
$menu['items'][$itemId]['Naam']."</a></li>\n";
$html .= buildMenu($itemId, $menu);
}
}
$html .= "</ul> \n";
}
return $html;
}
?>
Example CSS:
.section-navigation
{ float: left;
width: 16%;
background-color: #03bafd;
padding-bottom: 20px;
}
.section-navigation h3 {
color: white;
margin: 3%;
padding-bottom: 10.5px;
border-bottom: 2px solid #fff;
}
.section-navigation ul
{
margin: 0;
padding: 0;
padding-left: 1em;
list-style-type: none;
}
.section-navigation ul li a {
display: block;
padding: 12px 13px;
color: #fff;
text-decoration: none;
}
.section-navigation ul li a:hover{
color: #333;
background: #fff;
font-weight: bold;
}
.section-navigation ul > ul li
{
padding-left: 1em;
}