Home >Backend Development >PHP Tutorial >How to Group Array Data by Multiple Columns and Sum Values in Groups?

How to Group Array Data by Multiple Columns and Sum Values in Groups?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 13:18:02515browse

How to Group Array Data by Multiple Columns and Sum Values in Groups?

Group Array Data by Multiple Columns and Sum Values in Groups

In this situation, it is necessary to group multidimensional array data based on two column values ('part' and 'type') and sum the values of a specific column ('count') within each group. Given an input array ($arr1) as described, the desired output ($arr2) represents the grouped data with summed count values for each combination of 'part' and 'type'.

To achieve this result, a custom function can be utilized:

<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>

In this function:

  • The $output array is created to store the grouped data.
  • Each element of $input is iterated over.
  • The key for the $output element is created by concatenating the 'part' and 'type' values.
  • The values in $output_element are assigned or updated accordingly.
  • Finally, array_values() is used to return the values of the $output array as a new array.

Alternatively, if both databases are on the same database server, the grouping and summation could be performed efficiently using SQL's GROUP BY feature.

The above is the detailed content of How to Group Array Data by Multiple Columns and Sum Values in Groups?. 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