我想使用PHP
及其foreach
循环生成导航菜单。因此,自#34; Home"项目与其他项目有点不同,我想打电话给他,并在某些条件下改变其风格。以下代码适用于除主页之外的所有其他菜单项,因为它由于某种原因将array
添加到<li>
标记。你能否说出我在这里犯的错误?
<?php
$menu = array("Home" => "http://mywebsite.com", "Projects" => "/projects/", "About" => "/about/", "Contact" => "/contact/");
foreach ($menu as $opis => $link)
{
if (strtolower($opis) == $_GET['go'])
{
$style = "class=\"active\"";
}
else
{
if (!$_GET['go'] || $_GET['go'] == "home")
{
$style[0] = "class=\"active\"";
echo $style[0] . " ";
}
}
echo "<li ".$style."><a href=".$link.">".$opis."</a></li>";
}
?>
答案 0 :(得分:0)
这是因为当$GET['go']
为home
时,您已为变量$ style添加了一个键 -
$style[0] = "class=\"active\"";
将其更改为$style = "class=\"active\"";
答案 1 :(得分:0)
您需要将$style
设置为''
。如果不这样做,一旦设置,您将在下一次迭代中保留class="active"
。
$menu = array("Home" => "http://mywebsite.com", "Projects" => "/projects/",
"About" => "/about/", "Contact" => "/contact/");
if(empty($_GET['go'])) $_GET['go'] = 'home';
foreach ($menu as $opis => $link)
{
$style = (strtolower($opis) == $_GET['go']) ? "class=\"active\"" : '';
echo "<li $style><a href='$link'>$opis</a></li>\n";
}