Home >Backend Development >PHP Tutorial >How to Group and Sum Columns in a 2D PHP Array?
Grouping and Summing Columns in a 2D Array
The task is to process a PHP array of data, where each element represents a row, and each row consists of two columns: url_id and time_spent. The goal is to group the rows by the url_id column and sum the values in the time_spent column for each group.
Solution:
We can use PHP's array_count_values() function to achieve this:
<code class="php">$ts_by_url = array_count_values(array_column($array, 'url_id'));</code>
The array_column() function extracts the url_id column from the input array, producing an array of url_id values. The array_count_values() function then counts the occurrences of each url_id value, effectively grouping the rows.
However, this solution only provides a count of the occurrences for each url_id. To sum the time_spent values within each group, we need to modify the approach:
<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>
In this updated approach, we maintain an array $ts_by_url that will hold the sum of time_spent values for each url_id. We iterate through the input array, checking for each row if the corresponding url_id is already present in $ts_by_url. If not, we initialize it with a value of 0. Regardless, we add the time_spent value to the corresponding url_id entry in $ts_by_url.
This approach allows us to group the rows by url_id and sum the time_spent values for each group. The resulting $ts_by_url array will contain the desired sums, keyed by url_id.
The above is the detailed content of How to Group and Sum Columns in a 2D PHP Array?. For more information, please follow other related articles on the PHP Chinese website!