dongpai2754 2014-07-17 13:43
浏览 46

将数组拆分为多个并在新数组中添加下两个项目

I have an array, like:

$list = array('a', 'b', 'c', 'd', 'e',
              'f', '1', '2', '3', '4',
              '5', '6', '7', '8', '9');

And I want to split this array, and add every next two items in a new array as a group, like:

$new_list = array(
    array('a', 'b'),
    array('c', 'd'),
    array('e', 'f'),
    array('1', '2'),
    array('3', '4'),
    array('5', '6'),
    array('7', '8'),
    array('9'), // note that this one here is alone!
);

But I want to do this with foreach or something. I only know I can divide length of my array with 2 and use round or floor PHP functions to get a whole number, but I can't figure out how to group items of this array in two items per array.

Please help me, my brain is overflowing...

  • 写回答

1条回答 默认 最新

  • dongzan2740 2014-07-17 13:58
    关注
    $list = ['a', 'b', 'c', 'd', 'e',
        'f', '1', '2', '3', '4',
        '5', '6', '7', '8', '9'];
    
    $list2 = [];
    
    $c = 0;
    $temp_array = [];
    for ($i = 0; $i < Count($list); $i++)
    {
        $c++;
        array_push($temp_array, $list[$i]);
        if ($c >= 2)
        {
            array_push($list2, $temp_array);
            $temp_array = [];
            $c = 0;
        }
    }
    
    print_r($list2);
    
    echo '<br />List2: ' . count($list2) . '<br />List: ' . count($list);
    

    EDIT: or the solution which Mark Baker provided with the array_chunk() function. It's less code.

    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)