Grouping 2D Array Rows by Column and Summing Another Column
To obtain a grouped and summed result from a 2D array based on a specific column, we can employ the following technique:
<code class="php">// Assume we have an array $array containing the data as described in the question. $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']; }</code>
The loop iterates through the array and accumulates the time spent for each unique URL ID in the $ts_by_url array. By the end of the loop, the $ts_by_url array contains the grouped and summed results, with the keys representing the URL IDs and the values representing the total time spent for each URL ID.
Example Output:
<code class="php">print_r($ts_by_url); // Output: // Array // ( // [2191238] => 41 // [2191606] => 240 // == 215 + 25 // )</code>
The above is the detailed content of How to Group 2D Array Rows by Column and Sum Another Column?. For more information, please follow other related articles on the PHP Chinese website!