按顺序在5项后添加div

时间:2014-08-02 12:07:37

标签: php

我需要在每5个项目后添加一个div标签。任何人都可以提供这种逻辑的任何帮助,我已经尝试但没有成功。

我有这段代码:

<div class="product-grid">
    <?php foreach ($products as $product) { ?>
    <div class="item">.....</div>
    <?php } ?>
  </div>

我明白

<div class="product-grid">
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
 </div>

看起来像这样:(按顺序在5个项目后添加div。)

<div class="product-grid">
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="clearfix visible-xs-block"></div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="item">.....</div>
    <div class="clearfix visible-xs-block"></div>
    <div class="item">.....</div>
 </div>

一些帮助将不胜感激。

4 个答案:

答案 0 :(得分:5)

<?php 
// control variable 
$counter = 0;
?>
<div class="product-grid">
    <?php foreach ($products as $product) { ?>
        <div class="item">.....</div>
        <?php 
        // on every #5 result
        if(++$counter % 5 === 0) { ?>
          <div class="clearfix visible-xs-block"></div>
        <?php  
        }
    } 
    ?>
  </div>

答案 1 :(得分:0)

使用MOD运算符:

<div class="product-grid">
    <?php
        $i = 0;
        foreach ($products as $product) {
            $i++;
            if($i % 5 == 0){
    ?>
                <div class="clearfix visible-xs-block"></div>
    <? } ?>
        <div class="item">.....</div>
    <?php } ?>
</div>

答案 2 :(得分:0)

因为,每六个项目获得该特定课程,您可以使用临时计数器来跟踪:

<div class="product-grid">
    <?php
      $i = 1;
      foreach ($products as $product) {
        if( $i % 6 != 0 ) {
    ?>
    <div class="item">.....</div>
    <?php
        }
        else {
    ?>
    <div class="clearfix visible-xs-block"></div>
    <?php
        }
        $i++;
      }
    ?>
</div>

答案 3 :(得分:0)

You can do it like this:

<div class="product-grid">
   <?php
        $i = 1;
        foreach ($products as $product) {
            echo '<div class="item">.....</div>';
          if($i%5 == 0){
              echo '<div class="clearfix visible-xs-block"></div>';
          }  
          $i++;
        }
   ?> 
</div>