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] =&开发者_如何学编程gt; 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...
精彩评论