如果循环数是偶数,则将循环减半

时间:2019-05-14 19:05:38

标签: php loops break

我想将循环分成循环总数的一半。如果总循环数为奇数,我想删除最后一个数组项,以使总循环数为偶数,然后将已删除的项添加到后一半。

这是演示循环的代码结构-

<?php
$faqs = new WP_Query( array (
    'post_type' => 'faq'
));
?>
<div class="row">
   <div class="col-lg-6">
      <!-- The first half of the tootal loop count. -->
      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>
   </div>
   <div class="col-lg-6">
      <!-- The second half of the tootal loop count. -->
      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>
   </div>
</div>

我不知道如何根据我提到的条件控制循环。这就是为什么我无法尝试循环控制的原因。

2 个答案:

答案 0 :(得分:1)

在一个循环中。希望它会起作用。无法测试,因此,如果您遇到任何情况,请允许我。

<?php
$faqs = new WP_Query([
    'post_type' => 'faq',
    'post_status' => 'publish',
]);
$half = intval($faqs->post_count / 2);
$counter = 0;
?>
<div class="row">
    <div class="col-lg-6">
    <?php while ($faqs->have_posts()) : $faqs->the_post(); ?>
        <?php if ( $counter === $half ) : ?>
            </div><div class="col-lg-6">
        <?php endif; ?>

        <?php the_content(); ?>
    <?php ++$counter; endwhile; ?>
    </div>
</div>

答案 1 :(得分:0)

像这样尝试

<?php
$faqs = new WP_Query( array (
    'post_type' => 'faq'
));
?>
<div class="row">
   <div class="col-lg-6">
      <!-- The first half of the total loop count. -->
      <?php
      $i=0;
      while ($faqs->have_posts() && $i < $faqs->post_count / 2) : $faqs->the_post(); $i++
          the_content();
      endwhile();
      ?>
   </div>
   <div class="col-lg-6">
      <!-- The second half of the tootal loop count. -->
      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>
   </div>
</div>

https://wordpress.stackexchange.com/questions/27116/counting-the-posts-of-a-custom-wordpress-loop-wp-query