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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-09 09:15:02901browse

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

Group and Sum 2D Array Data by Columns

In this programming scenario, the objective is to group rows of a 2D array by one column's values (e.g., 'dd') and subsequently sum the values of another column ('quantity') within each group. The result is a reduced 2D array with unique 'dd' values and aggregated quantity information.

Example:

Consider the following input array:

[
    ['quantity' => 5,  'dd' => '01-Nov-2012'],
    ['quantity' => 10, 'dd' => '01-Nov-2012'],
    ['quantity' => 3,  'dd' => '02-Nov-2012'],
    ['quantity' => 4,  'dd' => '03-Nov-2012'],
    ['quantity' => 15, 'dd' => '03-Nov-2012'],
]

The desired output array would be:

[
    ['quantity' => 15, 'dd' => '01-Nov-2012'],
    ['quantity' => 3,  'dd' => '02-Nov-2012'],
    ['quantity' => 19, 'dd' => '03-Nov-2012'],
]

Solution using PHP:

To achieve this data transformation, we can utilize PHP's built-in arrays and looping capabilities:

// Input array
$in = array(array());

// Create output array
$out = array();

// Iterate through input rows
foreach ($in as $row) {
    // Check if 'dd' key exists in output array
    if (!isset($out[$row['dd']])) {
        // Initialize entry for 'dd' with empty quantity
        $out[$row['dd']] = array(
            'dd' => $row['dd'],
            'quantity' => 0,
        );
    }

    // Accumulate quantity for 'dd' key
    $out[$row['dd']]['quantity'] += $row['quantity'];
}

// Adjust output array to numerical indexing
$out = array_values($out);

// Display output array
var_dump($out);

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