Skip to content
Advertisement

PHP sum elements of two multi dimensional arrays

This is my first post on StackOverflow.

I am looking for the best way to take two arrays that each has a different amount of data items, merge them, but summing together the items that have the same value on one of the keys (using PHP).

Input arrays:

$array1 = array ( 
    0 => array ( 'result_date' => '2020-07-20', 'total_for_day' => '75', ), 
    1 => array ( 'result_date' => '2020-07-21', 'total_for_day' => '17', ), 
    2 => array ( 'result_date' => '2020-07-22', 'total_for_day' => '0', ), 
    3 => array ( 'result_date' => '2020-07-23', 'total_for_day' => '6', ), 
    4 => array ( 'result_date' => '2020-07-24', 'total_for_day' => '1', )
);
$array2 = array ( 
    0 => array ( 'result_date' => '2020-07-01', 'total_for_day' => '6264', ), 
    1 => array ( 'result_date' => '2020-07-02', 'total_for_day' => '7008', ), 
    2 => array ( 'result_date' => '2020-07-20', 'total_for_day' => '1968', ), 
    3 => array ( 'result_date' => '2020-07-21', 'total_for_day' => '7776', ), 
);

Desired output:

array ( 
    0 => array ( 'result_date' => '2020-07-01', 'total_for_day' => '6264', ), 
    1 => array ( 'result_date' => '2020-07-02', 'total_for_day' => '7008', ), 
    2 => array ( 'result_date' => '2020-07-20', 'total_for_day' => '2043', ), 
    3 => array ( 'result_date' => '2020-07-21', 'total_for_day' => '7793', ), 
    4 => array ( 'result_date' => '2020-07-22', 'total_for_day' => '0', ), 
    5 => array ( 'result_date' => '2020-07-23', 'total_for_day' => '6', ), 
    6 => array ( 'result_date' => '2020-07-24', 'total_for_day' => '1', )
);

So basically just merge the two arrays into one bigger array, but sum together the ‘total_for_day’ where the ‘result_date’ matched. Please note that in the desired output it is also being ordered by the ‘result_date’ ASC.

Thanks in advance 🙂

Advertisement

Answer

I would just take the simple approach and use an intermediate array mapping:

$array1 = array(...);
$array2 = array(...);
$arrayN = array(...);

$merged = array();
foreach (array_merge($array1, $array2, $arrayN) as $record) {
    $date = $record["result_date"];
    if (!isset($merged[$date])) {
        $merged[$date] = 0;
    }
    $merged[$date] += $record["total_for_day"];
}

$result = array();
foreach ($merged as $date => $days) {
    $result[] = array(
        "result_date" => $date, 
        "total_for_day" => "{$days}" // Remove the quotes if you don't want a string.
    );
}

usort($result, function ($a, $b) {
    return $a["result_date"] <=> $b["result_date"];
});

var_dump($result);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement