如果循环计数是偶数,则将循环分成两半

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


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


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

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


慕容708150
浏览 148回答 2
2回答

慕少森

在一个循环中。希望它会起作用。无法测试,所以如果您遇到任何情况,请告诉我。<?php$faqs = new WP_Query([&nbsp; &nbsp; 'post_type' => 'faq',&nbsp; &nbsp; 'post_status' => 'publish',]);$half = intval($faqs->post_count / 2);$counter = 0;?><div class="row">&nbsp; &nbsp; <div class="col-lg-6">&nbsp; &nbsp; <?php while ($faqs->have_posts()) : $faqs->the_post(); ?>&nbsp; &nbsp; &nbsp; &nbsp; <?php if ( $counter === $half ) : ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div><div class="col-lg-6">&nbsp; &nbsp; &nbsp; &nbsp; <?php endif; ?>&nbsp; &nbsp; &nbsp; &nbsp; <?php the_content(); ?>&nbsp; &nbsp; <?php ++$counter; endwhile; ?>&nbsp; &nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP