在foreach中做行换行

时间:2014-10-09 16:09:34

标签: php loops foreach

我想让4柱包裹一个.row容器,下面是我尝试的但是最后一行不是我想要的..如何删除最后一行使其正确

<div class="article-list-container">
  <?php $column_count = 1; ?>
  <div class="row">

  <?php foreach ($data_select_top_hits['article'] as $each_data_select_top_hits) { ?>
    <div class="article-list">
      <!-- .. -->
    </div>

      <?php if (($column_count % 4) == 0) { ?>
    <div class="clear"></div>
  </div>
  <div class="row">
      <?php } ?>
      <?php $column_count++;?>
    <?php } ?>
    <div class="clear"></div>
  </div>
</div>

输出

<div class="article-list-container">
  <div class="row">
    <div class="article-list"></div>
    <div class="article-list"></div>
    <div class="article-list"></div>
    <div class="article-list"></div>
    <div class="clear"></div>
  </div>
  <div class="row">
    <div class="article-list"></div>
    <div class="article-list"></div>
    <div class="article-list"></div>
    <div class="article-list"></div>
    <div class="clear"></div>
  </div>
  <div class="row">
    <div class="clear"></div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情。将行添加到数组中,然后遍历该数组并包装行。

<?php
$column_count = 1; 
foreach ($data_select_top_hits['article'] as $each_data_select_top_hits) { 
$row_chunk.="<div class='article-list'>$each_data_select_top_hits</div>"; 
if (($column_count % 4) == 0) { 
$chunk_array[]=$row_chunk;
$row_chunk="";
} 
$column_count++;
} 
?>
<div class="article-list-container">
<?php foreach($chunk_array as $rows){ ?>
<div class="row">
<?php echo $rows; ?>
<div class="clear"></div>
</div>
<?php } ?>
</div>