Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I merge the second and the third, the fourth and the fifth, the sixth and the seventh, ... values of a 2-dimensional array? The first array [number] should not be merged:

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

merged to:

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

I need somehow combine the array_merge_recursive() function and the foreach loop...

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Here's a solution using 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));

And here's a working demo.

share|improve this answer
    
Awesome, it works perfectly! Thank you really much! –  Felix Bernhard Feb 13 at 17:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.