php group by SUM using multi dimensional array

前端 未结 3 1433
离开以前
离开以前 2020-11-28 16:33

I have a php array like this:

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


        
3条回答
  •  一生所求
    2020-11-28 16:55

    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
    

提交回复
热议问题