Home > Backend Development > PHP Tutorial > How to Merge Associative Arrays with Summed Values for Shared Keys?

How to Merge Associative Arrays with Summed Values for Shared Keys?

Patricia Arquette
Release: 2024-11-04 12:14:29
Original
600 people have browsed it

How to Merge Associative Arrays with Summed Values for Shared Keys?

Merge Associative Arrays with Summed Values for Shared Keys

Merging multiple associative arrays while combining values for shared keys can be a common yet challenging task. This article presents several solutions to address this issue.

Array Merge with Summation

The goal is to merge two or more flat associative arrays (arrays with string keys and non-array values) and sum the values associated with identical keys. This differs from the default behavior of array_merge() function which replaces values for duplicate keys.

Examples

Consider the following example:

<code class="php">$a1 = array("a" => 2, "b" => 0, "c" => 5);
$a2 = array("a" => 3, "b" => 9, "c" => 7, "d" => 10);</code>
Copy after login

If we were to use array_merge() to combine these arrays, the result would be:

<code class="php">$a3 = array_merge($a1, $a2);
print_r($a3); </code>
Copy after login

Output:

Array
(
    [a] => 3
    [b] => 9
    [c] => 7
    [d] => 10
)
Copy after login

As you can see, the values for shared keys ("a", "b", "c") are not summed but replaced.

Custom Solutions

To achieve the desired result, we can utilize a custom function that iterates over the keys of the combined arrays and sums the values for shared keys. Here's one such implementation:

<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

Output:

<code class="php">Array
(
    [a] => 5
    [b] => 9
    [c] => 12
    [d] => 10
)</code>
Copy after login

This function allows us to merge multiple arrays with shared keys and provides the summed values for those keys.

The above is the detailed content of How to Merge Associative Arrays with Summed Values for Shared Keys?. 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