Search code examples
phparraysdatetimesumgrouping

Group 2d array by date portion of datetime column and sum another column


I have a 2d array with a datetime column and a subtotal column. I need to group the rows by the date portion of their datetime value and sum the subtotal values in each group.

Sample input array:

[
    ['id' => 81, 'placed' => '2013-09-19 16:32:53', 'sub_total' => 786],
    ['id' => 80, 'placed' => '2013-09-19 16:32:06', 'sub_total' => 780],
    ['id' => 79, 'placed' => '2013-09-18 17:06:48', 'sub_total' => 786],
    ['id' => 78, 'placed' => '2013-09-18 17:05:02', 'sub_total' => 756],
    ['id' => 77, 'placed' => '2013-09-17 17:02:53', 'sub_total' => 786],
    ['id' => 76, 'placed' => '2013-09-16 17:02:53', 'sub_total' => 756],
]

Desired output:

[
    ['placed' => '2013-09-19', 'sub_total' => 1566],
    ['placed' => '2013-09-18', 'sub_total' => 1542],
    ['placed' => '2013-09-17', 'sub_total' => 786],
    ['placed' => '2013-09-16', 'sub_total' => 756],
]

Solution

  • I tested this also: http://phpfiddle.org/main/code/rzv-ngp

    $newarray = array();
    foreach ($array as $value){
        $temp = explode(" ", $value['placed']);
        $date = $temp[0];
        $total = (isset($newarray[$date]['sub_total']) ? $newarray[$date]['sub_total'] + $value['sub_total']: $value['sub_total']);
        $newarray[$date] = array('placed' => $date, 'sub_total' => $total);
    }
    
    print_r($newarray);