Home >Backend Development >PHP Tutorial >How to Sum Values for Shared Keys When Merging Associative Arrays?

How to Sum Values for Shared Keys When Merging Associative Arrays?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 14:16:30214browse

How to Sum Values for Shared Keys When Merging Associative Arrays?

Merging Arrays and Summing Shared Key Values

The need often arises to merge multiple associative arrays while combining the values associated with shared keys. By default, array merging overwrites conflicting values, as seen in the example provided. To address this, we present a range of approaches that effectively add values for shared keys while preserving unique keys.

Using Array Intermediates:

One approach is to calculate the sum of values manually using array intermediates. This involves iterating through the keys of the merged array and summing the values for each key across the input arrays.

$sums = array();
foreach (array_keys($a1 + $a2) as $key) {
    $sums[$key] = (isset($a1[$key]) ? $a1[$key] : 0) + (isset($a2[$key]) ? $a2[$key] : 0);
}

Mapping and Reduction:

Another method involves creating intermediate arrays with zero values for each unique key. These are then merged with the original arrays and mapped to calculate the sums.

$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));

Array Walking:

Similarly, you can use array walking to calculate the sums for shared keys.

$sums = array_fill_keys(array_keys($a1 + $a2), 0);
array_walk($sums, function (&$value, $key, $arrs) { $value = @($arrs[0][$key] + $arrs[1][$key]); }, array($a1, $a2));

Reusable Function with Dynamic Parameters:

Finally, you can create a reusable function that accepts an unlimited number of arrays and calculates the sum of values for shared keys.

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;
}

These solutions provide efficient ways to merge multiple associative arrays and calculate the sum of values for shared keys, offering flexibility and code reusability for various scenarios.

The above is the detailed content of How to Sum Values for Shared Keys When Merging Associative Arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn