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

Barbara Streisand
Release: 2024-10-26 01:37:02
Original
280 people have browsed it

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>
    Copy after login
  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>
    Copy after login
  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>
    Copy after login
  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>
    Copy after login
  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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!