duan1979768678 2017-07-20 15:33
浏览 21
已采纳

PHP计数循环添加额外的行

I'm trying to wrap every 3 articles in a div so that my HTML would like like this:

<div class="row">
  <article>Article One</article>
  <article>Article Two</article>
  <article>Article Three</article>
</div>
<div class="row">
  <article>Article Four</article>
  <article>Article Five</article>
  <article>Article Six</article>
</div>

Below is my PHP. This is what I currently have, however an extra row is being added at the beginning, which I do not want.

$i = 0;
echo '<div class="row">';
if ($my_query->have_posts()) : 
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php if($i % 3 == 0) {echo '</div><div class="row">';}?>

The above prints the following:

<div class="row"></div> //I don't want this to be in the HTML
<div class="row">
  <article>Article One</article>
  <article>Article Two</article>
  <article>Article Three</article>
</div>
<div class="row">
  <article>Article Four</article>
  <article>Article Five</article>
  <article>Article Six</article>
</div>

I tried changing $i = 0 to $i = 1 but this didn't work either. This prints this in the markup:

    <div class="row">
      <article>Article One</article>
      <article>Article Two</article>
    </div>
    <div class="row">
      <article>Article Three</article>
      <article>Article Four</article>
      <article>Article Five</article>
    </div>
    <div class="row">
      <article>Article Six</article>
    </div>

I've tried different number combinations but I couldn't seem to get it simply wrap every 3 articles.

  • 写回答

3条回答 默认 最新

  • dongzhi9457 2017-07-20 15:40
    关注

    Write your condition as below:-

    if(!empty($i) && $i % 3 == 0)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?