Home >Backend Development >PHP Tutorial >How can I group a multidimensional array by multiple column values and sum another column's values?

How can I group a multidimensional array by multiple column values and sum another column's values?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-05 22:49:021083browse

How can I group a multidimensional array by multiple column values and sum another column's values?

Grouping Multidimensional Array Data by Multiple Column Values and Summing Column Values

Problem:

This problem involves an array with data from multiple database queries across different databases. The goal is to group the array elements based on two column values ("part" and "type") and calculate the sum of a third column ("count") for each group.

Array Example:

<code class="php">$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]
];</code>

Desired Output:

<code class="php">$arr2 = [
    ['part' => '1', 'type' => '1', 'count' => 15],
    ['part' => '2', 'type' => '1', 'count' => 10],
    ['part' => '2', 'type' => '2', 'count' => 5]
];</code>

Solution:

To group the array elements and sum the "count" values, the following function can be used:

<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']) && $output_element['count'] = 0;
    $output_element['count'] += $value['count'];
  }

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

This function iterates through the input array, identifying the "part" and "type" values for each element. It then uses these values as keys to create or retrieve output elements. For each key, the function initializes a "count" field if it doesn't exist and increments it with the value of that element's "count" field. Finally, it returns an array containing the grouped elements.

The above is the detailed content of How can I group a multidimensional array by multiple column values and sum another column's values?. 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