PHP - 每4次将一个div添加到foreach循环中

时间:2012-01-06 05:30:28

标签: php

我需要一个foreach循环的帮助。

基本上我需要做的是每4个循环在数据输出周围包装一个div。

我有以下循环:

foreach( $users_kicks as $kicks ) {
    echo $kicks->brand;
}

每4次回复我想把它包装成最后它会是这样的:

<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>
<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>
<div>
    kicks brand
    kicks brand
    kicks brand
    kicks brand
</div>

等等。

干杯

6 个答案:

答案 0 :(得分:118)

$count = 1;
foreach( $users_kicks as $kicks ) 
{
    if ($count%4 == 1)
    {  
         echo "<div>";
    }
    echo $kicks->brand;
    if ($count%4 == 0)
    {
        echo "</div>";
    }
    $count++;
}
if ($count%4 != 1) echo "</div>"; //This is to ensure there is no open div if the number of elements in user_kicks is not a multiple of 4

答案 1 :(得分:90)

这个答案很晚 - 但是如果人们看到它 - 这是一个更清洁的解决方案,没有凌乱的计数器和if声明:

foreach (array_chunk($users_kicks, 4, true) as $array) {
    echo '<div>';
    foreach($array as $kicks) {
         echo $kicks->brand;
    }
    echo '</div>';
}

您可以阅读array_chunk on php.net

答案 2 :(得分:19)

尝试%模数运算符。

$i=1;
//div begins
foreach( $users_kicks as $kicks ) {
   if($i % 4 ==0)
    {
      //div ends
      //div begins
    }
    echo $kicks->brand;
   $i++;
}
//div ends

答案 3 :(得分:2)

你也可以使用 array_chunk 来按块切割数组

$blocks = array_chunk($users_kicks, 4);
foreach ($blocks as $block) {
    echo '<div>';
    foreach ($block as $kicks) {
        echo $kicks->brand;
    }
    echo '</div>';
}

答案 4 :(得分:0)

对AVD的答案进行一点修改,以确保如果数组为空或者计数为4,则确保没有空DIV ......

if($lastRec=count($user_kicks)){
  echo '<div>';
  $i=1;
  foreach( $users_kicks as $kicks ) {
    if( ($i % 4 == 0) && ($i<$lastRec) ) echo '</div><div>';
    echo $kicks->brand;
    $i++;
  }
  echo '</div>';
}

答案 5 :(得分:0)

<?php
$item_count=1;
$items_block=3;
?>
<div class="wrapper">
    <?php if(!empty($list)){ ?>

        <div class="item_block">
            <?php foreach ($list as $val){ ?>
                <div>Item</div>

                <?php 
                if($item_count % $items_block==0){ ?>
                    </div>
                    <div class="item_block">
                <?php 
                } 
                $item_count++;
                ?>

            <?php endforeach; ?>
        </div>
    <?php } ?>
</div>