Foreach,为每三个添加课程

时间:2014-03-04 18:06:51

标签: php

我有一些PHP问题。我有一个用foreach显示的数组 代码如下所示:

foreach($names as $key => $name):

echo $name;

endforeach;

假设有6个名字,那么它会输出:

Name1
Name2
Name3
Name4
Name5
Name6

现在我需要的是在div中分组三个名字。喜欢这个

<div class="group">
Name1
Name2
Name3
</div>
<div class="group">
Name4
Name5
Name6
</div>

但实际上我不知道该怎么做,我尝试了一些不起作用的东西。

构建这个的最佳方法是什么?

提前致谢!如果有什么不清楚我需要更好地解释,请告诉我。

3 个答案:

答案 0 :(得分:1)

$count = 1;
foreach($names as $key => $name):
if$count == 1)
{
echo '<div class="group">';
}

echo $name;
$count++;
if($count == 3)
{
echo '</div>';
$count = 1;

}

endforeach;

我讨厌在foreach中计算,但它似乎是最简单的解决方案,也许是一个已经被计算的for循环更适合。

答案 1 :(得分:1)

这将是我的解决方案:

$names=array("peter", "tom", "felix", "patrick", "paul", "sam", "bill");

foreach($names as $key => $name){
    //if the key is 0 we just started and have to open a div
    if($key==0){
        echo '<div class="group">';
    }

    //actually echo the name in our div
    echo $name;

    //if the key can be divided by 3 we have to close our div
    //we add one because index starts with 0
    $close=is_int(($key+1)/3);

    //and we want to close the div if there is no more element in our array
    if(!array_key_exists($key+1, $names)){
       $close=true;
    }


    if($close){
        //close the div 
        echo '</div>';
        //if there is another element in our array we have to open the tags again
        if(array_key_exists($key+1, $names)){
            echo '<div class="group">';
        }
    }
}

答案 2 :(得分:0)

echo '<div class="group">'
$index = 0;

foreach($names as $key => $name):

echo $name;
$index++;
if($index%3==0)
{
echo '</div>'
echo '<div class="group">'
}
endforeach;
echo '</div>'