askerman
askerman

Reputation: 49

Merge two "m-Y"-keyed arrays and sum the values of intersecting keys, then sort by year then month

I want to merge two associative arrays and sum their values where both arrays have the same key.

$first = [
    '01-1970' => 0.00,
    '03-2019' => 4350.00,
    '05-2019' => 150.00,
    '06-2019' => 50.00,
];

$second = [
    '03-2019' => 0.00,
    '04-2019' => 0.00,
    '06-2019' => 34.83,
];

Desired result:

[
    '01-1970' => 0.00,
    '03-2019' => 4350,
    '04-2019' => 0.00,
    '05-2019' => 150.00,
    '06-2019' => 84.83,
]

Upvotes: 1

Views: 5476

Answers (9)

mickmackusa
mickmackusa

Reputation: 47874

There is no need to iterate over the first array if because by definition all of its keys will be guaranteed to be unique. Directly save the first array to the result.

Then iterate over the second array and add its values to corresponding jeys in the result array or merely store the element if the key is new to the result.

If you need your "little-endian" keys to be sorted, use uksort() and reformat the keys to be "big-endian".

Code: (Demo)

$result = $first;
foreach ($second as $k => $v) {
    $result[$k] = ($result[$k] ?? 0) + $v;
}
uksort(
    $result,
    fn($a, $b) => preg_replace('/(\d+)-(\d+)/', '$2-$1', $a)
                  <=>
                  preg_replace('/(\d+)-(\d+)/', '$2-$1', $b)
);
var_export($result);

Upvotes: 0

AterLux
AterLux

Reputation: 4654

$result = $first_array; // just copy array into result

// scan second array
foreach ($second_array as $k => $v) {
   // if key already exists, then add, else just set
   $result[$k] = isset($result[$k]) ? ($result[$k] + $v) : $v;
}

// done
print_r($result);

Upvotes: 1

treyBake
treyBake

Reputation: 6560

You can make use of a function I made:

<?php
    function array_sum_multi($arrayOne, $arrayTwo)
    {
        # get rid of keys
        $valuesOne = array_values($arrayOne);
        $valuesTwo = array_values($arrayTwo);

        //create return array
        $output = [];

        # loop that shizzle
        for ($i = 0; $i < count($valuesOne); $i++)
        {
            $output[$i] = $valuesOne[$i] + (!empty($valuesTwo[$i]) ? $valuesTwo[$i] : 0);
        }

        return $output;
    }

    $result = array_sum_multi([0.00, 4350.00, 150.00, 50.00], [0.00, 0.00, 34.83]);

    # then for your keys:
    $result = array_combine(array_keys($yourFirstArray), $result);

    echo '<pre>'. print_r($result, 1) .'</pre>';

Upvotes: 2

Vamshi Rockzz
Vamshi Rockzz

Reputation: 71

Try this simple method thank you,

$sum = [];
foreach($firstArray as $key => $value){
    if(array_key_exists($key,$secondArray)){
        $newArray = [$key=>$value+$secondArray[$key]]; 
        $sum = array_merge($sum,$newArray);
    }else{
        $newArray = [$key=>$value]; 
        $sum = array_merge($sum,$newArray);
    }
}

//your final required result
var_dump($sum);

Upvotes: 0

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You can use array_keys to get the unique from both of the array and then loop through keys to some them

$r = [];
$keys = array_keys($a1+$a2);
foreach($keys as $v){
  $r[$v] = (empty($a1[$v]) ? 0 : $a1[$v]) + (empty($a2[$v]) ? 0 : $a2[$v]);
}

Working DEMO

Upvotes: 3

Geee
Geee

Reputation: 2249

Try this,

$a1 = array (
        '01-1970' => 0.00,
        '03-2019' => 4350.00,
        '05-2019' => 150.00,
        '06-2019' => 50.00
    );

$a2 = array (
        '03-2019' => 0.00,
        '04-2019' => 0.00,
        '06-2019' => 34.83
    );

$sums = array();
foreach (array_keys($a1 + $a2) as $key) {
    $sums[$key] = @($a1[$key] + $a2[$key]);
}

echo "<pre>";
print_r($sums);

Here is some other solution you can use.

Cheer!

Upvotes: -1

Qirel
Qirel

Reputation: 26450

Your best bet is to loop the arrays individually, and sum up the values into a resulting array as you go. We can create a new array that contains the two arrays them to shorten our code a bit (see how we define [$first, $second] as the first loop).

This removes any problems with mixed lengths, and keeps all the keys and values in the array intact.

$result = [];
// Loop over our two arrays, here called $first and $second
foreach ([$first, $second] as $a) {
    // Loop over the values in each array
    foreach ($a as $k=>$v) {
        // If the index is new to the $result array, define it to be zero (to avoid undefined index notices) 
        if (!isset($result[$k]))
            $result[$k] = 0;

        // Sum up the value!
        $result[$k] += $v;
    }
}
print_r($result);

Upvotes: 3

Dylan KAS
Dylan KAS

Reputation: 5663

An easy way to implement it would be to loop through each array, and add it to a common array with the same key.

Looping through only one array would result in a lack of a few elements if the first array is smaller than the second one or if some element from the second array are not present in the first one.

So let's just loop through both of them and add it to sum.

$sum = [];

foreach($firstArray as $key => $value){
  $sum[$key] = $value + (isset($sum[$key]) ? $sum[$key] : 0.0);
}
foreach($secondArray as $key => $value){
  $sum[$key] = $value + (isset($sum[$key]) ? $sum[$key] : 0.0);
}

print_r($sum);

Upvotes: 0

Mike Foxtech
Mike Foxtech

Reputation: 1651

$sumArray = [];

foreach($firstArray as $key => $value) {
    $sumArray[$key] = $value + ($secondArray[$key] ?? 0);
}

Upvotes: -2

Related Questions