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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-09 03:26:02169browse

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

Grouping and Summing Data in a 2D Array

In this scenario, you aim to group the rows of a 2D array based on a specific column's values and then sum another column's values within each group.

Input Data:

[
    ['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'],
];

Desired Result:

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

Implementation:

To achieve this, follow these steps:

  1. Iterate through the input array's rows.
  2. For each row:

    • Check if the grouped array contains an entry indexed by the current row's 'dd' value.
    • If not, create an entry with the 'dd' value and an initial 'quantity' of 0.
    • Increment the 'quantity' value of the grouped array entry by the current row's 'quantity'.
  3. Convert the grouped array into a numerically indexed array using array_values().

The following PHP code demonstrates this process:

$in = array(array()); // your input
$out = array();
foreach ($in as $row) {
    if (!isset($out[$row['dd']])) {
        $out[$row['dd']] = array(
            'dd' => $row['dd'],
            'quantity' => 0,
        );
    }
    $out[$row['dd']]['quantity'] += $row['quantity'];
}
$out = array_values($out); // make the out array numerically indexed
var_dump($out);

This approach effectively groups the input data by the 'dd' column and sums the 'quantity' column values for each group, producing the desired output.

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