Search code examples
phparraysmultidimensional-arraysumgrouping

Group 2d array rows by one column and sum another column


I have a php array like this:

[
    ['url_id' => 2191238, 'time_spent' => 41],
    ['url_id' => 2191606, 'time_spent' => 215],
    ['url_id' => 2191606, 'time_spent' => 25]
]

How to get the SUM of time_spent based on group by url_id (using array_count_values?)?


Solution

  • Why not a simpler

    $ts_by_url = array();
    foreach($array as $data) {
        $ts_by_url[ $data['url_id'] ] += $data['time_spent'];
    }