I am trying to sum the values of two associative arrays. This is the first array:
Array
(
[Jan 01, 2013] => Array
(
[COM] => 100
[
Most directly/simply, iterate the levels of your second array and determine if the values should be appended to the first array, or merge-summed into it.
Code: (Demo)
$arr1 = [
"Jan 01, 2013" => ["COM" => 100, "RES" => 200, "FOO" => 5],
"Oct 28, 2014" => ["COM" => 300, "RES" => 400]
];
$arr2 = [
"Jan 01, 2013" => ["COM" => 10, "RES" => 20],
"Oct 28, 2014" => ["COM" => 30, "RES" => 40]
];
foreach ($arr2 as $date => $set) {
foreach ($set as $key => $val) {
if (!isset($arr1[$date][$key])) { // val is unique to 1st array, set it
$arr1[$date][$key] = $val;
} else { // val already exists in 1st array, add 2nd val to 1st val
$arr1[$date][$key] += $val;
}
}
}
var_export($arr1);
Because you don't know the subarray keys for your incoming data and you have associative keys, you can use array_merge_recursive()
to merge your two arrays in a way that sets up very simple summing.
After merging based on associative values, you can loop the new multi-dimensional array. While iterating, signify the subarray and the subarray's values as "modifiable by reference" -- this means that the foreach loops will process the actual array rather than a copy of the array. Effectively, this will make the changes affect the new array and deliver the desired result via $assoc_merged
.
Code: (Demo)
$arr1 = [
"Jan 01, 2013" => ["COM" => 100, "RES" => 200, "FOO" => 5],
"Oct 28, 2014" => ["COM" => 300, "RES" => 400]
];
$arr2 = [
"Jan 01, 2013" => ["COM" => 10, "RES" => 20],
"Oct 28, 2014" => ["COM" => 30, "RES" => 40]
];
$assoc_merged =array_merge_recursive($arr1, $arr2);
// var_export($assoc_merged); // see what this makes
foreach ($assoc_merged as $date => &$set) {
foreach ($set as $key => &$val) {
$val = array_sum((array)$val);
// (array) forces a lone value to be an array containing one element; avoids generating Warnings
}
}
var_export($assoc_merged);
Both approaches produce the same output:
array (
'Jan 01, 2013' =>
array (
'COM' => 110,
'RES' => 220,
'FOO' => 5,
),
'Oct 28, 2014' =>
array (
'COM' => 330,
'RES' => 440,
),
)