【问题标题】:Counter using foreach in php在php中使用foreach进行计数器
【发布时间】:2013-03-18 15:39:10
【问题描述】:

我正在尝试让我的计数器进行计数。我正在尝试使用以下内容在显示的每一秒帖子中添加一个类名(偶数):

<?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 部分)现在用

添加到每个帖子中

【问题讨论】:

  • 使用模数运算符:if (($c++ % 2) == 0) { 但在你的 foreach 循环中使用 inside
  • $c 看起来总是 1。您可能希望将 if 语句移到 foreach 中。

标签: php wordpress loops foreach count


【解决方案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; ?>

【讨论】:

    【解决方案2】:

    从这部分代码:

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

    【讨论】:

    • 只是门票。谢谢你的帮助!解释得很好,所以完全理解。谢谢!
    【解决方案3】:

    问题是您没有在 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2020-12-06
      相关资源
      最近更新 更多