php foreach 为key,每两个数字为一组

2021-12-26 00:00:00 foreach php
<?php
$data=array('1','2','3','4','5','6','7','8','9','10','11');
foreach($data as $key=> $element){
    if($key % 2 != 0){
        echo $element.'<br />';
    }
    echo '<hr />';
}
?>

php foreach 作为key,如何让每两个数字为一组?

php foreach as key, how to make every two number as a group?

我要输出:

1,2
_____
3,4
_____
5,6
_____
7,8
_____
9,10
_____
11

推荐答案

查看 array_chunk() 函数.

Have a look at the array_chunk() function.

在你的情况下,你会像这样使用它:

In your case you'd use it like this:

foreach(array_chunk($data, 2) as $values) {
    echo implode(',', $values)."
";
}

在最后一次迭代中 $values 将只有一个元素,所以如果你打算使用它们的索引直接访问元素,请记住使用 count() 来检查数组的元素计数.

During the last iteration $values will have only one element so if you plan to access the elements directly using their index remember to use count() to check the array's element count.

相关文章