phparraysmultidimensional-arraysummerging-data

Sum the values of two associative multi-dimensional arrays in PHP


I am trying to sum the values of two associative arrays. This is the first array:

Array
(
[Jan 01, 2013] => Array
    (
        [COM] => 100
        [RES] => 200
    )

[Oct 28, 2014] => Array
    (
        [COM] => 300
        [RES] => 400
    )
)

and this is the second array:

Array
(
[Jan 01, 2013] => Array
    (
        [COM] => 10
        [RES] => 20
    )

[Oct 28, 2014] => Array
    (
        [COM] => 30
        [RES] => 40
    )
)

I need to sum the values from these two arrays so that it produces this result:

    Array
(
[Jan 01, 2013] => Array
    (
        [COM] => 110
        [RES] => 220
    )

[Oct 28, 2014] => Array
    (
        [COM] => 330
        [RES] => 440
    )
)

I found this tutorial to sum values of associative arrays, but it does not seem to work with my multi-dimensional arrays. Any suggestions how to accomplish this? Thank you.


Solution

  • Use foreach() for first array & check the key of first array whether it exist or not in second array. If exist the calculate sum. Example:

    $arr1 = Array
    (
        "Jan 01, 2013" => Array
        (
            "COM" => 100,
            "RES" => 200,
        ),
    
        "Oct 28, 2014" => Array
        (
            "COM" => 300,
            "RES" => 400,
        )
    );
    $arr2 = Array
    (
        "Jan 01, 2013" => Array
        (
            "COM" => 10,
            "RES" => 20,
        ),
    
        "Oct 28, 2014" => Array
        (
            "COM" => 30,
            "RES" => 40,
       )
    );
    
    $arr3 = array();
    foreach($arr1 as $key => $val):
        if(array_key_exists($key, $arr2)):
            $arr3[$key]["COM"] = $val["COM"] + $arr2[$key]["COM"];
            $arr3[$key]["RES"] = $val["RES"] + $arr2[$key]["RES"];
        endif;
    endforeach;
    
    print '<pre>';
    print_r($arr3);
    print '</pre>';
    

    Output:

    Array
    (
        [Jan 01, 2013] => Array
            (
                [COM] => 110
                [RES] => 220
            )
    
        [Oct 28, 2014] => Array
            (
                [COM] => 330
                [RES] => 440
            )
    
    )