我对生成的多级菜单有疑问。我希望每个菜单级别选择另一种颜色(li class=menucolor)。但是,我设法只做到了第一级和第二级。我不能把第二层和第三层分开。请帮忙。
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'),
和代码:
<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>