简体   繁体   中英

How to merge two arrays using PHP based on index?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM