2013-03-18 3 views
0

저는 카운터를 얻으려고합니다. 나는 다음과 같은 사용하여 표시 매 초마다 게시물에 클래스 명을 (심지어) 추가하려고 해요 : 난 그냥 even 클래스 이름이 출력되는 것을 얻을하지 않습니다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; ?> 

. 출력 얻을 수있는 유일한 클래스 이름은

+0

계수 연산자를 사용하여'경우 (($ foreach 루프 내부에서 수행한다. –

+0

'$ c'는 항상 1과 같아 보인다. if 문을 foreach 내부로 옮길 수있다. – Jrod

답변

0

는 :

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

당신은 foreach 루프 내부의 증가 및 if-else 블록을 넣어해야합니다. 이와 같이 :

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

1

체크 아웃 또한 modulus operator

으로 순간에 모든 게시물에 추가하여 짝수/홀수 검사를 이동 (문이 경우 내의 다른 부분에서) animatedFadeIn 클래스입니다 귀하의 게시물 루프에. 코드의이 부분에서

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

문제는 다른 문장에서 카운터를 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; 
관련 문제