Reputation: 18123
I have this simple setup:
$array1 = array(0 => array(0 => array('amount' => '49')));
$array2 = array(0 => array(0 => array('amount' => '149')));
$mergetest = array_merge_recursive($array1, $array2);
This outputs:
array(2) {
[0]=>
array(1) {
[0]=>
array(1) {
["amount"]=>
string(2) "49"
}
}
[1]=>
array(1) {
[0]=>
array(1) {
["amount"]=>
string(3) "149"
}
}
}
It should merge in such way, that the output should be like this instead:
array(1) {
[0]=>
array(2) {
[0]=>
array(1) {
["amount"]=>
string(2) "49"
}
[1]=>
array(1) {
["amount"]=>
string(3) "149"
}
}
}
Since array index 0 already exists, and so does the array inside it - so it should match by child array instead of parent and in that way add the next child array to it.
Can this be done in a clean way without building a custom function that loops through and checks?
UPDATE
A solution, that also works with:
$array1 = array(0 => array(0 => array('amount' => '49')));
$array2 = array(1243 => array(0 => array('amount' => '49'), 1 => array('amount' => '449')));
Where the output is expected to be in separate parent arrays (0 and 1243), just like the first above output.
Upvotes: 0
Views: 73
Reputation: 2330
<?php
$array1 = array(0 => array(0 => array('amount' => '49')));
$array2 = array(0 => array(0 => array('amount' => '149')));
$result = array_map('array_merge', $array1, $array2);
var_dump($result);
?>
And the output will be like the below.
array(1) {
[0]=>
array(2) {
[0]=>
array(1) {
["amount"]=>
string(2) "49"
}
[1]=>
array(1) {
["amount"]=>
string(3) "149"
}
}
}
NOTE : array_merge_recursive() will fail because it appends numeric keys, not merging them:
UPDATE ANSWER FOR ARRAYS WITH DIFFERENT INDEXES
<?php
$array1 = array(0 => array(0 => array('amount' => '49')));
$array2 = array(1243 => array(0 => array('amount' => '49'), 1 => array('amount' => '449')));
$keys = array_unique(array_merge(array_keys($array1), array_keys($array2)));
foreach ($keys as $key) {
if (array_key_exists($key, $array1) && array_key_exists($key, $array2)) {
$array3[$key] = array_merge($array1[$key], $array2[$key]);
} elseif (array_key_exists($key, $array1)) {
$array3[$key] = $array1[$key];
} else {
$array3[$key] = $array2[$key];
}
}
var_dump($array3);
?>
And the output will be
array(2) {
[0]=>
array(1) {
[0]=>
array(1) {
["amount"]=>
string(2) "49"
}
}
[1243]=>
array(2) {
[0]=>
array(1) {
["amount"]=>
string(2) "49"
}
[1]=>
array(1) {
["amount"]=>
string(3) "449"
}
}
}
Upvotes: 1
Reputation: 843
You can get the result you want if you use string keys at the top level rather than integers.
You have two levels of integer-indexed arrays but it seems that to you they have a different nature because you need them to be merged differently. PHP has no way to know that, so with this setup no standard function can do what you need. You will need to change the data structure to mark that difference (e.g. by using string keys on first level and integers on the second) or write a custom merge function here.
Upvotes: 0