Given a PHP array containing 2D rows with specific columns, a common task is to group the rows based on a particular column and aggregate the values from another column.
For example, consider the following array:
<code class="php">[ ['url_id' => 2191238, 'time_spent' => 41], ['url_id' => 2191606, 'time_spent' => 215], ['url_id' => 2191606, 'time_spent' => 25] ]</code>
The goal is to calculate the sum of the "time_spent" column for each unique value in the "url_id" column. One possible solution involves using a loop to iterate over the array:
<code class="php">$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>
After processing the entire array, the $ts_by_url array will contain the sum of "time_spent" for each unique "url_id":
<code class="php">2191238 => 41 2191606 => 240 // == 215 + 25</code>
This approach effectively groups the rows by "url_id" and aggregates the "time_spent" values. It leverages the associative array nature of PHP to efficiently store and update values based on the "url_id" key.
The above is the detailed content of How to Group 2D Array Rows by a Single Column and Aggregate Another Column in PHP?. For more information, please follow other related articles on the PHP Chinese website!