0

How can i merge these two arrays:

First Array:

[0] => Array
    (
        [0] => Array
            (
                [id] => 10
            )

        [1] => Array
            (
                [id] => 21
            )

    )

Second Array:

[1] => Array
    (
        [0] => Array
            (
                [id] => 11
            )

        [1] => Array
            (
                [id] => 22
            )

        [2] => Array
            (
                [id] => 13
            )

    )

I want the result to be:

[0][id]=>10
[1][id]=>11
[2][id]=>21
[3][id]=>22
[4][id]=>13
1
  • am I right that you want use I from first, then from second,then from first, then from second? Commented Aug 21, 2011 at 9:23

1 Answer 1

3
$array1 = array(
    array('id' => 10),
    array('id' => 21),
);
$array2 = array(
    array('id' => 11),
    array('id' => 22),
    array('id' => 13),
);
$new_array = array();

$length = max(count($array1), count($array2));

for ($i = 0; $i < $length; $i++)
{
  if (isset($array1[$i]))
    array_push($new_array, $array1[$i]);
  if (isset($array2[$i]))
    array_push($new_array, $array2[$i]);
}
print_r($new_array);

For me this outputs:

Array (
    [0] => Array ( [id] => 10 )
    [1] => Array ( [id] => 11 )
    [2] => Array ( [id] => 21 )
    [3] => Array ( [id] => 22 )
    [4] => Array ( [id] => 13 )
)

Edit: Used max to optimize it a bit as RiaD said. Edit2: Forgot to add $ in front of many i variables...

Sign up to request clarification or add additional context in comments.

1 Comment

it's not so good, to calculate count() two times for 1 array, you can use max(count($arr1),count($arr2)) instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.