Search code examples
phparraysmultidimensional-arraysumgrouping

Group rows of data by 3 columns and sum another column within respective groups


I have the php array like this:

Array
(
    [0] => Array
        (            
            [time_stamp] => 1287484988
            [date_time] => Tuesday, 19 October 2010 16:13:7
            [day] => 19
            [month] => 10
            [year] => 2010
            [time_spent] => 41
        )

    [1] => Array
        (         
            [time_stamp] => 1287484662
            [date_time] => Tuesday, 19 October 2010 16:7:41
            [day] => 19
            [month] => 10
            [year] => 2010
            [time_spent] => 215           
        )
)

Suppose in january the total number of days is: 31

How do I loop through the number of days(31) to get the SUM of time_spent(time_spent for every day for a given month) using GROUP BY time_stamp where day=$day,month=$month,year=$year using php.


Solution

  • The basic version would be

    $sums = array();
    
    foreach ($your_array as $entry) {
       if (!isset($sums[$entry['year']]) {
            $sums[$entry['year']] = array();
       }
       if (!isset($sums[$entry['year']][$entry['month']]) {
            $sums[$entry['year']][$entry['month']] = array();
       }
       if (!isset($sums[$entry['year']][$entry['month']][$entry['day']]) {
            $sums[$entry['year']][$entry['month']][$entry['day']] = 0;
       }
    
       $sums[$entry['year']][$entry['month']][$entry['day']] += $entry['time_spent'];
    }
    

    Ugly, but the 3 if() prevent various warnings from being spit out as the $sums array is built.