在php中使用foreach的计数器
问题描述:
我试图让我的柜台,以及计数。我想添加一个类名(偶数)到每一秒后用下面显示的:在php中使用foreach的计数器
<?php
global $paged;
global $post;
$do_not_duplicate = array();
$categories = get_the_category();
$category = $categories[0];
$cat_ID = $category->cat_ID;
$myposts = get_posts('category='.$cat_ID.'&paged='.$paged);
$do_not_duplicate[] = $post->ID;
$c = 0;
$c++;
if($c == 2) {
$style = 'even animated fadeIn';
$c = 0;
}
else $style='animated fadeIn';
?>
<?php foreach($myposts as $post) :?>
// Posts outputted here
<?php endforeach; ?>
我只是不明白被输出的even
类名。这得到输出的唯一的类名是animated
和FadeIn
类(从我的if语句else部分)被添加到每一个岗位,此刻与
答
从你的这部分代码:
$c = 0;
$c++;
if($c == 2) {
$style = 'even animated fadeIn';
$c = 0;
}
else $style='animated fadeIn';
你需要把增量和if-else
块foreach
循环中。像这样:
<?php foreach($myposts as $post) :
$c++;
if($c % 2 == 0) {
$style = 'even animated fadeIn';
$c = 0;
}
else $style='animated fadeIn'; ?>
// Posts outputted here
<?php endforeach; ?>
+0
只是票。谢谢你的帮助!解释得很好,所以完全理解它。谢谢! – egr103 2013-03-18 15:57:35
答
此外,移动你的偶/奇校验到你的帖子循环。
<?php $i = 0; foreach($myposts as $post) :?>
<div class="<?php echo $i % 2 ? 'even' : 'odd'; ?>">
// Posts outputted here
</div>
<?php $i++; endforeach; ?>
答
问题是你不要在你的else语句中将计数器重新设置为2。
if($c == 2) {
$style = 'even animated fadeIn';
$c = 0;
} else {
$style='animated fadeIn';
$c = 2;
}
话虽这么说,你也可以使用模如其他人所说或者干脆:
//outside loop
$c = 1;
//inside loop
if ($c==1)
$style = 'even animated fadeIn';
else
$style='animated fadeIn';
$c = $c * -1;
,甚至更短的
//outside
$c = 1;
//inside
$style = (($c==1)?'even':'').' animated fadeIn';
$c = $c * -1;
使用模运算符:'如果(($ C++%2)== 0){'但是在你的foreach循环中做'内部' – 2013-03-18 15:40:57
'$ c'看起来像它总是1.你可能想把你的if语句移到你的'foreach'中。 – Jrod 2013-03-18 15:43:05