Home  >  Article  >  Backend Development  >  How to Group 2D Array Rows by a Single Column and Aggregate Another Column in PHP?

How to Group 2D Array Rows by a Single Column and Aggregate Another Column in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 00:19:28481browse

How to Group 2D Array Rows by a Single Column and Aggregate Another Column in PHP?

Grouping 2D Array Rows by a Single Column and Aggregating Another Column

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn