php group by SUM using multi dimensional array

I have a php array like this:

 Array
    (
        [0] => Array
            (
                [url_id] => 2191238
                [time_spent] => 41

            )

        [1] => Array
            (
                [url_id] => 2191606
                [time_spent] => 215

            )
        [2] => Array
            (
                [url_id] => 2191606
                [time_spent] => 25

            )
    )

So, how to get the SUM of time_spent based on group by url_id (using array_count_values)


Solution 1:

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