我的数组包含动态数量的元素。 它们分为4个。所以
array
[0] -> "group one"
[1] -> "group one"
[2] -> "group one"
[3] -> "group one"
[4] -> "group two"
[5] -> "group two"
[6] -> "group two"
[7] -> "group two"
[8] -> "group three"
[9] -> "group three"
[10] -> "group three"
[11] -> "group three"
我想要做的是在一个循环中输出并测试每个组中的所有元素,然后添加,然后对下一个组执行相同操作。
我怀疑它应该很容易..使用计数器来跟踪多少输出等,但显然我的大脑在这个问题上无法正常工作:)
感谢任何困扰我的人:)
答案 0 :(得分:1)
看看array_chunk。
<?php
foreach(array_chunk(range(1, 12), 4) as $index => $chunk) {
echo "Printing Chunk $index\n";
foreach($chunk as $number) {
echo "$number\n";
}
}
/*
Printing Chunk 0
1
2
3
4
Printing Chunk 1
5
6
7
8
Printing Chunk 2
9
10
11
12
*/
安东尼。
答案 1 :(得分:0)
<?php
$length = count($array);
// the first element of each group is indexed by $i
// so the second element can be accessed by $i + 1, the third by $i + 2, ...
for($i = 0; $i < $length; $i += 4)
{
echo "1. element: " . $array[$i];
echo "2. element: " . $array[$i+1];
echo "3. element: " . $array[$i+2];
echo "4. element: " . $array[$i+3];
// do something
}
?>