2013-03-18 123 views
0

我試圖讓我的櫃檯,以及計數。我想添加一個類名(偶數)到每一秒後用下面顯示的:在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類名。這得到輸出的唯一的類名是animatedFadeIn類(從我的if語句else部分)被添加到每一個崗位,此刻與

+0

使用模運算符:'如果(($ C++%2)== 0){'但是在你的foreach循環中做'內部' – 2013-03-18 15:40:57

+0

'$ c'看起來像它總是1.你可能想把你的if語句移到你的'foreach'中。 – Jrod 2013-03-18 15:43:05

回答

0

從你的這部分代碼:

$c = 0; 
    $c++; 
    if($c == 2) { 
     $style = 'even animated fadeIn'; 
     $c = 0; 
    } 
    else $style='animated fadeIn'; 

你需要把增量和if-elseforeach循環中。像這樣:

<?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

1

退房的modulus operator

此外,移動你的偶/奇校驗到你的帖子循環。

<?php $i = 0; foreach($myposts as $post) :?> 
    <div class="<?php echo $i % 2 ? 'even' : 'odd'; ?>"> 
     // Posts outputted here 
    </div> 
<?php $i++; endforeach; ?> 
0

問題是你不要在你的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;