Home >Backend Development >PHP Tutorial >How to Group 2D Array Rows by Column and Sum Another Column in PHP?
Grouping 2D Array Rows by Column and Summing Another Column
Given a multidimensional PHP array with rows containing columns named 'url_id' and 'time_spent', one may seek to group these rows by 'url_id' and calculate the sum of 'time_spent' for each group.
To accomplish this:
Iterate through the array:
<code class="php">foreach($array as $data) {</code>
Check if an array key exists for the current 'url_id':
<code class="php"> if(!array_key_exists($data['url_id'], $ts_by_url)) {</code>
Create an entry in the $ts_by_url array for the 'url_id' and initialize it to 0 if it doesn't already exist:
<code class="php"> $ts_by_url[ $data['url_id'] ] = 0;</code>
Add the 'time_spent' value to the $ts_by_url array corresponding to the 'url_id':
<code class="php"> $ts_by_url[ $data['url_id'] ] += $data['time_spent']; }</code>
Example Output:
<code class="php">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 in PHP?. For more information, please follow other related articles on the PHP Chinese website!