我需要在每个div中显示3个独特的产品

时间:2016-10-07 12:45:15

标签: php codeigniter

我需要在每个div中显示3个独特的产品,例如:Sample output

如何在一个循环中获得不同的产品?目前在下面的代码中,我得到了相同的产品3次。

A.Controller

来自控制器:

<?php
    foreach ($rows as $display) {
?>
        <div class="col-md-4 col-sm-6">
             <div class="section-title">
                 <div class="pull-right pr-icon">
                      <i class="fa fa-diamond"></i> Top Suppliers 
                 </div>
                 <div class="main-title">
                      <b>  Selected Products</b>
                 </div>
                 <div class="sub-title">
                     Source the latest items
                 </div>
             </div>
             <div class="row">
                  <div class="col-md-4">
                      <img src="<?php echo 'data:image;base64,'.$display->image; ?>" class="img-responsive image product-item" />
                      <div class="product-description">
                         <p class="text-center"><?php echo $display->name; ?></p>
                         <a href="<?php echo base_url(); ?>index.php/itemcontroller/itemFetch?id=<?php echo $display->name; ?>"><p class="desc-btn">VIEW</p></a>
                      </div>
                  </div>
              </div> 
         </div>  
    <?php
    }
    ?>

型号代码:

public function index()
{
    $this->load->database();
    $data['rows']=$this->homemodel->fetchData();
    $this->load->view('home',$data);
    $this->load->library('image_lib');
}

1 个答案:

答案 0 :(得分:0)

<?php
$chunkedArray  = array_chunk($rows, 3); //productList Array, number of chunks/parts
foreach($chunkedArray as $newRow) {
    echo '<div class="row">';
    foreach ($newRow as $display) {
?>
        <div class="col-md-4 col-sm-6">
             <div class="section-title">
                 <div class="pull-right pr-icon">
                      <i class="fa fa-diamond"></i> Top Suppliers 
                 </div>
                 <div class="main-title">
                      <b>  Selected Products</b>
                 </div>
                 <div class="sub-title">
                     Source the latest items
                 </div>
             </div>
             <div class="row">
                  <div class="col-md-4">
                      <img src="<?php echo 'data:image;base64,'.$display->image; ?>" class="img-responsive image product-item" />
                      <div class="product-description">
                         <p class="text-center"><?php echo $display->name; ?></p>
                         <a href="<?php echo base_url(); ?>index.php/itemcontroller/itemFetch?id=<?php echo $display->name; ?>"><p class="desc-btn">VIEW</p></a>
                      </div>
                  </div>
              </div> 
         </div>  
    <?php
    }
    echo '</div>';
}
    ?>

array_chunk会做的工作.. 了解更多array_chunk here