这可能是愚蠢的简单,但我想找到一种方法将类添加到无序列表,然后在每第三个项后交替该类.
我只是为每三个项目添加一个类(这不是我想要的),但这是我的代码:
<?php $i=1; foreach($this->items as $item) : ?>
<li class="<?php if ($i % 3 == 0) : ?>odd<?php endif; ?>"><a href="<?php echo $linky; ?>">xxx</a></li>
<?php $i++; endforeach; ?>
Run Code Online (Sandbox Code Playgroud)
吐出来的:
<li class="">xxx</li>
<li class="">xxx</li>
<li class="odd">xxx</li>
<li class="">xxx</li>
<li class="">xxx</li>
<li class="odd">xxx</li>
Run Code Online (Sandbox Code Playgroud)
但我希望得到的是:
<li class="odd">xxx</li>
<li class="odd">xxx</li>
<li class="odd">xxx</li>
<li class="even">xxx</li>
<li class="even">xxx</li>
<li class="even">xxx</li>
Run Code Online (Sandbox Code Playgroud)
等等.通常我会用jquery做这样的事情,但在这种情况下我必须使用php ..任何帮助都会非常感激:)
使用每次都翻转(否定)的布尔标志$i % 3 == 0:
// Start with 0 instead of 1
$i=0;
// Flag starts TRUE
$state = TRUE;
foreach ($this->items as $item) {
if ($i % 3 === 0) {
// Flip to opposite state
$state = !$state;
}
?>
<li class="<?php if ($state) : ?>odd<?php else: ?>even<?php endif; ?>"><a href="<?php echo $linky; ?>">xxx</a></li>
<?php
$i++;
}
Run Code Online (Sandbox Code Playgroud)
这是一个演示.虽然您需要检查输出以查看类更改.