我尝试按组在循环中显示数据,实际上我有一个包含许多元素的数组,需要在4、5等的组中显示
我举了一个例子:
$array_values=array(
"2","3","5","2","3","5","2","3","5","2","3","5","2","3","5","2","3",
"5","2","3","5","2","3","5","2","3","5","2","3","5"
);
$c=0;
foreah($array_values as $array_value) {
print $array_value
if($c%3) {
print "<br><br>";
}
$c++;
}
正如你在例子中看到的,在这种情况下,我想放"<br>",循环中的每个3个元素,在其他情况下可以是每个4个或更多的元素,我尝试了这个,但没有得到好的结果,在某些情况下显示良好,在其他情况下显示所有糟糕的
我不知道该怎么做,感谢的帮助
与所有解决方案一样,有多种方法可以做到这一点。
您可以使用array_slice
从数组中一次获取值3。
for ($c = 0; $c < count($array_values); $c+=3) {
print(implode(array_slice($array_values, $c, 3)));
print "<br><br>";
}
您还可以使用array_chunk
将阵列分解为3位段:
foreach (array_chunk($array_values, 3) as $row) {
print(implode($row));
print "<br><br>";
}
您需要检查$c%3
的余数是否为0。但如果你想在另一种情况下增加另一个长度,你就必须加上它。但这应该让你开始。
$array_values=array("2","3","5","2","3","5","2","3","5","2","3","5","2","3","5","2","3","5","2","3","5","2","3","5","2","3","5","2","3","5");
$c=1;
foreach($array_values as $array_value)
{
print $array_value;
if($c%3 === 0)
{
print "<br><br>";
}
$c++;
}
运行时,我会得到以下输出:
235
235
235
235
235
235
235
235
235
235