Home >Backend Development >PHP Tutorial >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 = &$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>
In this function:
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!