Home >Backend Development >PHP Tutorial >How to Merge and Sum Values of Shared Keys in Flat Associative Arrays?
Merge and Sum Values in Flat Associative Arrays
Problem:
You have multiple flat associative arrays and want to merge them, adding together the values associated with matching keys without overwriting existing values. The standard array_merge() function, as well as a simple addition operation, do not provide the desired behavior.
Solution:
To merge associative arrays and sum the values of shared keys, you can use one of the following approaches:
1. Loop over the Combined Keys:
<code class="php">$sums = array(); foreach (array_keys($a1 + $a2) as $key) { $sums[$key] = (isset($a1[$key]) ? $a1[$key] : 0) + (isset($a2[$key]) ? $a2[$key] : 0); }</code>
This approach loops through the keys of the combined arrays and accumulates the values for each key into the $sums array.
2. Use Mapping:
<code class="php">$keys = array_fill_keys(array_keys($a1 + $a2), 0); $sums = array_map(function ($a1, $a2) { return $a1 + $a2; }, array_merge($keys, $a1), array_merge($keys, $a2));</code>
Here, we create an array with all the unique keys from the input arrays and then use array_map() to map a function that sums the values associated with each key in the arrays.
3. Helper Function:
If you frequently need to perform this operation, you can create a helper function:
<code class="php">function array_sum_identical_keys() { $arrays = func_get_args(); $keys = array_keys(array_reduce($arrays, function ($keys, $arr) { return $keys + $arr; }, array())); $sums = array(); foreach ($keys as $key) { $sums[$key] = array_reduce($arrays, function ($sum, $arr) use ($key) { return $sum + @$arr[$key]; }); } return $sums; }</code>
This function accepts any number of arrays and sums the values of shared keys into a new array.
By using one of these approaches, you can merge and sum the values of shared keys in flat associative arrays, resulting in the desired behavior.
The above is the detailed content of How to Merge and Sum Values of Shared Keys in Flat Associative Arrays?. For more information, please follow other related articles on the PHP Chinese website!