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

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

Susan Sarandon
Susan SarandonOriginal
2024-10-26 09:57:03378browse

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

Grouping 2D Array Rows by a Column and Summing Another Column

To group rows in a 2D array based on a specific column and sum another column, you can employ the following approach:

Suppose we have an array like this:

<code class="php">[
    ['url_id' => 2191238, 'time_spent' => 41],
    ['url_id' => 2191606, 'time_spent' => 215],
    ['url_id' => 2191606, 'time_spent' => 25]
]</code>

To calculate the sum of time_spent values for each unique url_id, we can use the following PHP code:

<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 code, we loop through the array and create an array ($ts_by_url) that is indexed by url_id. For each data item in the loop, we check if its url_id exists in $ts_by_url. If it does not, we set its value to 0. Then, we increment the time_spent value by the time_spent in the current data item.

After the loop finishes, $ts_by_url will contain the desired results:

2191238 => 41
2191606 => 240 // == 215 + 25

The above is the detailed content of How to Group Rows in a 2D Array by a Column and Sum 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