$a = array('matches' =>
array(
'5' => array('weight' => 6),
'15' => array('weight' => 6),
)
);
$b = array('matches' =>
array(
'25' => array('weight' => 6),
'35' => array('weight' => 6),
)
);
$merge = array_merge($a, $b);
print_r($merge);
The result of this script is
Array
(
[matches] => Array
(
[25] => Array
(
[weight] => 6
)
[35] => Array
(
[weight] => 6
)
)
)
But why?
I want the result was this:
Array
(
[matches] => Array
(
[5] => Array
(
[weight] => 6
)
[15] => Array
(
[weight] => 6
)
[25] => Array
(
[weight] => 6
)
[35] => Array
(
[weight] => 6
)
)
)
Because the key 'matches'
in the first array is being overwritten by the same key in the second. You need to do this instead:
$merge = array('matches' => array());
$a = array(
'matches' => array(
'5' => array('weight' => 6),
'15' => array('weight' => 6)
)
);
$b = array(
'matches' => array(
'25' => array('weight' => 6),
'35' => array('weight' => 6)
)
);
$merge['matches'] = array_merge($a['matches'], $b['matches']);
print_r($merge);
UPDATE
In order to preserve the numeric keys, you'll have to do this:
$merge['matches'] = $a['matches'] + $b['matches'];
If using the array union operator like this, just remember the following from php.net:
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.