I have a problem with the generated multi-level menu. I would like each menu level select another color (li class=menucolor). However, I managed to only the first and 2nd level do. I can’t separate the second level from the third level. Please help.
SQL:
CREATE TABLE IF NOT EXISTS `menu` (
`id` int(11) NOT NULL auto_increment,
`id_parent` int(11) NOT NULL default '0',
`link` varchar(255) NOT NULL,
`order` int(11) NOT NULL default '0',
`title` varchar(255) collate utf8_polish_ci NOT NULL default '',
PRIMARY KEY (`id`)
);
INSERT INTO `menu` (`id`, `id_parent`, `link`, `order`, `title`) VALUES
(1, 0, index.php, 3, 'Index'),
(3, 1, link1.php, 1, 'Art1'),
(4, 1, link2.php, 2, 'Art2'),
(5, 4, link2.php, 6, 'Other art'),
(6, 4, link2.php, 1, 'Art AAA'),
(7, 4, link2.php, 1, 'Art BBB'),
(8, 4, link2.php, 1, 'Art CCC'),
AND CODE:
<ul id="menu_left">
<?php
$menuArray = array();
$query = mysql_query(' select id, id_parent, link, order, title
from menu
order by order asc
');
while($row = mysql_fetch_array($query))
{
$menuArray[] = array( 'id' => $row['id'],
'id_parent' => $row['id_parent'],
'link' => $row['link'],
'order' => $row['order'],
'title' => $row['title']
);
}
function menu($id)
{
global $menuArray;
$hasChildren = false;
$resultArray = array();
if (empty($menuArray))
{
return;
}
foreach ($menuArray as $value)
{
if ($value['id_parent'] == $id)
{
$resultArray[] = $value;
}
}
foreach ($resultArray as $value)
{
if ($hasChildren === false)
{
$hasChildren = true;
if ($value['id_parent'] == 0)
{
$j++
?>
<!-- ul first -->
<?php
}
else
{
?>
<!-- <ul> -->
<?php
}
}
if($j=='1') {
echo '<li class="menucolor0">';
}
elseif($j!='1') {
echo '<li class="menucolor1">';
}
?>
<a href=<?php echo $value['link']; ?>"><?php echo $value['title']; ?></a>
<?php
menu($value['id']);
?>
</li>
<?php
}
if ($hasChildren === true)
{
<!-- </ul> -->
}
}
menu(0);
?>
</ul>
Any direct solution to this would be very slow, I suggest you update your table as such:
and here is how you display the menu in the desired order:
don’t forget to replace databasename, username and password in both scripts