PHP:在二维数组中合并数组

时间:2014-02-13 16:54:22

标签: php arrays loops multidimensional-array merge

如何合并二维数组的第二个和第三个,第四个和第五个,第六个和第七个......值?不应合并第一个数组[number]:

Array
(
[number] => Array
    (
        [0] => 1234
        [1] => 2345
        [2] => 3456
    )
[vote01] => Array
    (
        [0] => 000
        [1] => 000
        [2] => 001
    )
[vote02] => Array
    (
        [0] => 002
        [1] => 002
        [2] => 003
    )
[vote03] => Array
    (
        [0] => 004
        [1] => 004
        [2] => 005
    )
[vote04] => Array
    (
        [0] => 006
        [1] => 007
        [2] => 008
    )
    ...
)

合并到:

Array
(
[number] => Array
    (
        [0] => 1234
        [1] => 2345
        [2] => 3456
    )
[new01] => Array
    (
        [0] => 000
        [1] => 000
        [2] => 001
        [3] => 002
        [4] => 002
        [5] => 003
    )
[new02] => Array
    (
        [0] => 004
        [1] => 004
        [2] => 005
        [3] => 006
        [4] => 007
        [5] => 008
    )
    ...
)

我需要以某种方式结合array_merge_recursive()函数和foreach循环...

1 个答案:

答案 0 :(得分:0)

这是使用array_walk的解决方案:

array_walk($arr, function($item, $key, &$d) {
    if ($d[0]++ > 1 && $d[0] % 2) {
        $end = &$d[1][count($d[1]) - 1];
        $end = array_merge($end, $item);
    }
    else {
        $d[1][] = $item;
    }
}, array(0, &$newarr));

这是一个有效的demo