Home >Backend Development >PHP Tutorial >How do you group a multidimensional array by two columns and sum values for each group?

How do you group a multidimensional array by two columns and sum values for each group?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 01:16:02830browse

How do you group a multidimensional array by two columns and sum values for each group?

Grouping Multidimensional Array Data by Two Columns and Summing Values for Each Group

Consider an array created by combining results from two separate database queries, resembling the following:

$arr1 = [
    ['part' => '1', 'address' => 'aaa', 'type' => '1', 'count' => 5],
    ['part' => '1', 'address' => 'bbb', 'type' => '1', 'count' => 5],
    ['part' => '1', 'address' => 'ccc', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'aaa', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'bbb', 'type' => '1', 'count' => 5],
    ['part' => '2', 'address' => 'ccc', 'type' => '2', 'count' => 5]
];

The goal is to group this array by 'part' and 'type' columns and calculate the sum of 'count' values for each group.

To accomplish this, we can leverage the following function:

<code class="php">function groupByPartAndType($input) {
  $output = Array();

  foreach($input as $value) {
    $output_element = &amp;$output[$value['part'] . "_" . $value['type']];
    $output_element['part'] = $value['part'];
    $output_element['type'] = $value['type'];
    !isset($output_element['count']) &amp;&amp; $output_element['count'] = 0;
    $output_element['count'] += $value['count'];
  }

  return array_values($output);
}</code>

This function iterates through the input array and populates an output array with elements keyed by the combination of 'part' and 'type' values. For each output element, it sets the 'part', 'type', and 'count' fields appropriately, ensuring that the 'count' field is initialized to zero if not already set. The function returns an array of the values from the output array.

By applying this function to $arr1, we obtain the desired result:

$arr2 = [
    ['part' => '1', 'type' => '1', 'count' => 15],
    ['part' => '2', 'type' => '1', 'count' => 10],
    ['part' => '2', 'type' => '2', 'count' => 5]
];

The above is the detailed content of How do you group a multidimensional array by two columns and sum values for each group?. 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