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

Barbara Streisand
Release: 2024-10-27 03:31:03
Original
575 people have browsed it

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

Grouping 2D Array Rows by Column and Summing Another Column

To obtain a grouped and summed result from a 2D array based on a specific column, we can employ the following technique:

<code class="php">// Assume we have an array $array containing the data as described in the question.

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

The loop iterates through the array and accumulates the time spent for each unique URL ID in the $ts_by_url array. By the end of the loop, the $ts_by_url array contains the grouped and summed results, with the keys representing the URL IDs and the values representing the total time spent for each URL ID.

Example Output:

<code class="php">print_r($ts_by_url);
// Output:
// Array
// (
//     [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?. 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!