phparraysmultidimensional-arraysumgrouping

Calculate totals for each unique 2nd level data set in a 3d array


I am trying to calculate the total of unique DRIVER values in a multidimensional array.

Input:

$distance_covered = [
    '1_JAN_2017' => ['DRIVER_1' => [2, 5, 3],    'DRIVER_2' => [3, 2, 6, 9]],
    '2_JAN_2017' => ['DRIVER_1' => [3, 9],       'DRIVER_3' => [1, 4, 8]],
    '3_JAN_2017' => ['DRIVER_4' => [9],          'DRIVER_1' => [2, 7, 5, 2]], 
    '4_JAN_2017' => ['DRIVER_1' => [5, 3, 3, 2], 'DRIVER_4' => [4, 9, 8, 5]], 
    '5_JAN_2017' => ['DRIVER_2' => [8, 5],       'DRIVER_5' => [3, 9, 7]],
    '6_JAN_2017' => ['DRIVER_5' => [2, 1, 7, 5], 'DRIVER_4' => [1, 9, 6]], 
    '7_JAN_2017' => ['DRIVER_4' => [5, 2, 9],    'DRIVER_3' => [4, 1, 6]],
]; 

Desired result:

[
    'DRIVER_1' => 51,
    'DRIVER_2' => 33,
    'DRIVER_3' => 24,
    'DRIVER_4' => 67,
    'DRIVER_5' => 34
]

This is the sum of distance travelled by each driver in all trips

I tried code like this:

$res = array();
foreach($distance_covered as $value) {
    foreach($value as $key => $number) {
        (!isset($res[$key])) ?
            $res[$key] = $number :
            $res[$key] += $number;
    }
}
print_r($res);

Solution

  • This one works for me

    $res = array();
    foreach($distance_covered as $value)//the array which you have given us 
    {
        foreach($value as $key => $number) //loop over array of date
        {
            if(!isset($res[$key]))//check if the key exist in over defined array if no then run this
            {
                $res[$key] = array_sum($number);// Sum all distances of that driver
                continue;//set the key and continue the foreach... 
            }
            $res[$key] += array_sum($number);// Sum all distances of that driver    
        }
    }
    
    print_r($res);      
    die;
    

    And the Output is

    Array
    (
        [DRIVER_1] => 51
        [DRIVER_2] => 33
        [DRIVER_3] => 24
        [DRIVER_4] => 67
        [DRIVER_5] => 34
    )