0

I have the following array of brands:

$brand=array('brand1','brand2','brand3');

The goal is to create a link in the navigation menu for each of the brands, so I could run the following to achieve that:

sort($brand);
foreach ($brand as &$bval) {
$bval2 = strtolower($bval);
$bval3 = str_replace(" ", "-", $bval2);
echo '<li><a href="/?detail='.$bval3.'"';
//See note below
echo '><span>'.$bval.'</span></a></li>';
}

All of that works just fine. However, in order to indicate in the navigation menu which brand is selected, the link needs class="tactive" inside of it. In order to figure out which brand is selected, I could use something like what I have below and insert it where I have the //See note below comment in the code above. ($currentbrand would be defined in the file containing all of the page data):

if ($_GET[detail]=$currentbrand) {
echo 'class="tactive"';
}

However, in order for every link to not be marked as active, this would need to be done outside of the foreach loop. Could I interrupt the foreach loop, add the code that I need to, and then resume it in order to have the last part of the link there?

Thanks in advance.

4

1 回答 1

0

为了不将每个链接标记为活动,这需要在 foreach 循环之外完成

这是错误的假设。您真正需要做的是比较而不是分配

if ($_GET['detail'] == $currentbrand) {
  echo 'class="tactive"';
}

因为否则表达式将取决于$currentbrand是真还是假。


此外,您可以稍微重写代码并减少不需要的变量和字符串连接的数量。一个例子可能是:

sort($brand);
foreach ($brand as $bval) {
  $alias = str_replace(' ', '-', strtolower($bval));

  printf(
    '<li><a href="/?detail=%s" class="%s"><span>%s</span></a></li>',
    $alias,
    isset($_GET['detail']) && $alias === $_GET['detail'] ? 'tactive' : '',
    $bval
  );
}
于 2013-04-28T21:19:38.197 回答