How to Sum Values of Shared Keys When Merging Multiple Associative Arrays?

Patricia Arquette
Release: 2024-11-09 18:08:02
Original
617 people have browsed it

How to Sum Values of Shared Keys When Merging Multiple Associative Arrays?

Merging Multiple Flat Associative Arrays with Summation of Shared Keys

When combining associative arrays with the array_merge() function, values associated with shared keys tend to be replaced rather than summed. This poses a challenge when attempting to add the values of shared keys from multiple associative arrays.

To overcome this hurdle, one can adopt several approaches:

  • Foreach Iteration with Error Suppression:
<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>
Copy after login
  • Anonymous 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>
Copy after login
  • Combinational Solution:
<code class="php">$sums = array_fill_keys(array_keys($a1 + $a2), 0);
array_walk($sums, function (&amp;$value, $key, $arrs) { $value = @($arrs[0][$key] + $arrs[1][$key]); }, array($a1, $a2));</code>
Copy after login
  • Custom Function for Arbitrary Number of Arrays:
<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>
Copy after login

These approaches provide flexible solutions for merging multiple associative arrays and summing the values associated with shared keys.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template