php foreach 为key,每两个数字为一组 [英] php foreach as key, every two number as a group

查看:16
本文介绍了php foreach 为key,每两个数字为一组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?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.

这篇关于php foreach 为key,每两个数字为一组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆