一个包装内同时3物体或更少/的foreach在PHP [英] Wrapping 3 objects or less inside a while / foreach in PHP
问题描述
简单的问题。我有21个元素的数组,并显示出&LT内部每三个人; DIV>
块。在code是的的东西的是这样的:
Simple question. I have an array of 21 elements, and show every three of them inside a <div>
block. The code is something like this:
<?php
$faces= array(
1 => 'happy',
2 => 'sad',
(sic)
21 => 'angry'
);
$i = 1;
foreach ($faces as $face) {
echo $face;
$i++;
}
?>
问题在于,当这阵没有21元,有时它得到24,其他时间17.我如何包装每三个人,独自包裹休息吗?我想出了用开关
和情况
,但仅当只有21个元素。我想我可以<一个href=\"http://stackoverflow.com/questions/665135/find-the-last-element-of-an-array-while-using-a-foreach-loop-in-php\">count他们事先并把结束了最后一个(即使它是一组一个元素的)。
The problem lies when this array doesn't have 21 elements, sometimes it gets 24, an other times 17. How I wrap every three of them, and wrap alone the rest? I came up with using switch
and case
, but that works only when there are 21 elements only. I think I could count them beforehand and put a closing in the last one (even if it is a group of one element).
推荐答案
您已经有大部分是在这里。所有你缺少的东西来测试,如果你已经准备好包裹。你递增所以在 $ I
,请尝试:
You already have most of it here. All you're missing is something to test if you're ready to wrap. So before you increment $i
, try:
$i = 1;
foreach ($faces as $face)
{
echo $face;
if ($i % 3 == 0)
{
echo "<br />"; // or some other wrapping thing
}
$i++;
}
这将确保你每包3个面,留在最后的单位剩余部分。
This will ensure you're wrapping every 3 faces, leaving any remainder in the final unit.
这篇关于一个包装内同时3物体或更少/的foreach在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!