Group 2d array rows by one column and sum another column [duplicate]

Let’s pretend that $array contains our data. We will go through the array and continually add the time_spent to another array keyed by url_id.

$ts_by_url = array();
foreach($array as $data) {
    if(!array_key_exists($data['url_id'], $ts_by_url))
        $ts_by_url[ $data['url_id'] ] = 0;
    $ts_by_url[ $data['url_id'] ] += $data['time_spent'];
}

$ts_by_url should now contain:

2191238 => 41
2191606 => 240 // == 215 + 25

Leave a Comment