我有一个看起来像这样的foreach:
foreach ($blogusers as $bloguser) {
$args = array(
'author' => $bloguser->user_id,
'showposts' => 1,
'caller_get_posts' => 1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
$user = get_userdata($bloguser->user_id);
userphoto($bloguser->user_id, "<div class='all_authors'><a href='http://blogg.nacka.se/nastasteg/author/".$user->user_login . "'>","</a><ul><li><a href='http://blogg.nacka.se/nastasteg/author/".$user->user_login . "'>" .$user->user_firstname."</a></li><li class='occupation'>".$user->user_lastname."</li></ul></div>", array('width' => 135, 'height' => 135));
#echo "<div class='all_authors'><a href='http://blogg.nacka.se/nastasteg/author/".$user->user_login . "'><img src='http://www.gravatar.com/avatar/" . md5( strtolower( trim( " $user->user_email " ) ) )."?s=135' /></a><ul><li><a href='http://blogg.nacka.se/nastasteg/author/".$user->user_login . "'>" .$user->user_firstname."</a></li><li class='occupation'>".$user->user_lastname."</li></ul></div>";
}
}
在每个foth div中,想添加一个额外的课程。我该怎么做呢?
答案 0 :(得分:13)
使用模数运算符。我看到@Alex已经打败了我,但我提供了我编写和测试的代码,以便其他人可以更清楚地看到原理:
$blogusers=array('a','b','c','d','e','f','g','h','i','j');
$i=0;
foreach ($blogusers as $bloguser) {
if($i % 4 === 0) $extraclass= "fourthClass";
$resultHTML .= "<div class=\"standardClass $extraclass\">$bloguser</div>";
$i++;
$extraclass="";
}
echo $resultHTML;
使用三元运算符可以使其更紧凑,但这是原则。
答案 1 :(得分:7)
在foreach调用$ i之前创建一个变量并将其设置为0;
在你内部使用
$class = ($i%4 === 0) ? 'yourclass' : '';
$class
现在是'yourclass'或空字符串
然后在使用$i
$i++
结束时
答案 2 :(得分:0)
我会考虑在循环之前创建局部变量,在每次循环迭代时递增,在重要的循环迭代上执行操作并重置为0
答案 3 :(得分:0)
或许可以添加计数器?
$counter = "";
foreach($array AS $variable){
$counter +=1;
// Here you will do your standard stuff you do always
if($counter == 4){ // check for right counter value
$counter = ""; // null the counter again
// HERE you can do stuff that only happens every 4th iteration
}
// HERE you can carry on with your usual stuff that happens always
}
当然有很多不同的方法可以做到这一点,这在我眼里是简单的。