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

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

问题描述

 <?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 as key,如何让每两个数字作为一个组?
$ b

我想输出:

$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 3,4
_____
5,6
_____
7,8
_____
9,10
_____
11


解决方案

查看 array_chunk() 函数。 / p>

在这种情况下,您可以像这样使用它:

  foreach (array_chunk($ data,2)as $ values){
echo implode(',',$ values)。\\\
;





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


<?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 as key, how to make every two number as a group?

I want to output:

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

解决方案

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)."\n";
}

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作为关键,每两个数字作为一个组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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