PHP循环 - 检查每一次循环中
问题描述:
我想一个类添加到项目中在我的循环,每次是第二项有它上面的环形项目,所以像这样:PHP循环 - 检查每一次循环中
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
}
?>
答
正如评论所说,使用the modulo operator。特别为您的示例代码:
$i = 0;
while ($timeline = $fetchtimeline->fetch(PDO::FETCH_ASSOC)) {
$i++;
if ($i % 2 === 0) {
// add your class here
}
}
+0
似乎做的工作,谢谢 – Mitch
答
你可以使用一些
<?php
$array = [1,2,3,4,5,6,7,8,9];
foreach ($array as $a) {
if ($a % 2 == 0) {
echo $a;
}
}
答
使用的模量的计数器来跟踪你有多少个循环是,并确保你每一个成功的第二环复位。
$counter = 0;
while ($timeline = $fetchtimeline->fetch(PDO::FETCH_ASSOC)) {
if ($counter == 2) {
do_stuff_here
$counter = 0;
}
else {
$counter++;
}
}
+0
似乎没有工作,我用我现在的代码更新了问题 – Mitch
你的意思是每隔一行或你可以更具体? '模数运算符'浮现在脑海 – chris85
modulo http://php.net/manual/en/language.operators.arithmetic.php –
@ chris85啊,你编辑过。 *顽皮淘气*大声笑 –