我希望每次在它上面有一个循环项目时,在我的循环中为一个项添加一个类,所以像这样:
loopitem1
loopitem2 <- add class to this one
loopitem3
loopitem4 <- add class to this one
loopitem5
loopitem6 <- add class to this one
我该如何做到这一点?
我的循环看起来像这样:
while ($timeline = $fetchtimeline->fetch(PDO::FETCH_ASSOC)) {
}
提前致谢!
编辑;我现在拥有的东西;
<?php
$counter = 0;
while ($timeline = $fetchtimeline->fetch(PDO::FETCH_ASSOC)) {
$inverted = "";
if($counter == 2) {
$inverted = 'class="timeline-inverted"';
$counter = 0;
} else {
$counter++;
}
?>
<li <?php echo $inverted; ?>>
<div class="timeline-badge primary"><i class="fa fa-hashtag"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title"><?php echo $timeline['title']; ?></h4>
<p><small class="text-muted"><?php echo $engine->readable($timeline['timestamp']); ?> by <?php echo $engine->pullName($timeline['postedby']); ?></small></p>
</div>
<div class="timeline-body">
<p><?php echo $timeline['content']; ?></p>
</div>
</div>
</li>
<?php
}
?>
答案 0 :(得分:2)
使用计数器跟踪您所处的循环次数,并确保在每次成功的第二次循环时重置它。
$this->upload->initialize($config2);
答案 1 :(得分:1)
如评论所述,请使用the modulo operator。特别针对您的示例代码:
$i = 0;
while ($timeline = $fetchtimeline->fetch(PDO::FETCH_ASSOC)) {
$i++;
if ($i % 2 === 0) {
// add your class here
}
}
答案 2 :(得分:0)
你可以使用数字模数
<?php
$array = [1,2,3,4,5,6,7,8,9];
foreach ($array as $a) {
if ( $a % 2 == 0 ) {
echo $a;
}
}