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

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 01:37:02281browse

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:

  1. Iterate through the array:

    <code class="php">foreach($array as $data) {</code>
  2. 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>
  3. 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>
  4. 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>
  5. Now, the $ts_by_url array will contain the grouped result with 'url_id' keys and the sum of 'time_spent' as values.

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!

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