php 二维数组以某一键名进行分组相加
如题,如果是从数据库里取数据的时候大可以使用如下SQL
SELECT SUM(t_value),t_id FROM t_table GROUP BY t_id
但是如果是在php程序中处理类似的问题就稍微麻烦点了,这里给个函数就是处理类似的问题,实例代码如下:
- <?php
-
-
-
- function add_array($arr, &$new_arr, $target_key) {
- $num = count($new_arr);
- for ($i = 0; $i < $num; $i++) {
-
-
-
-
- if ($arr[$target_key] != $new_arr[$i][$target_key]) {
- $cmp_num++;
- } else {
- $tar_exist = true;
- $tar_key = $i;
- break;
- }
- }
-
- if ($cmp_num == $num)
- $tar_exist = false;
- if ($tar_exist) {
- foreach ($arr as $key => $value) {
- if ($key != $target_key) {
- $new_arr[$tar_key][$key]+=$value;
- }
- }
- } else {
-
-
-
-
-
- $new_arr[$num][$target_key] = $arr[$target_key];
- foreach ($arr as $key => $value) {
- if ($key != $target_key) {
- $new_arr[$num][$key]+=$value;
- }
- }
- }
- }
- $arr = array(
- array('group_id' => 13, 'team_price' => 88.00, 'satopay_price' => 85.00, 'team_id' => 348, 'origin' => 440, 'gain' => 14.45, 'quantity' => 5),
- array('group_id' => 13, 'team_price' => 12.00, 'satopay_price' => 11.00, 'team_id' => 344, 'origin' => 36, 'gain' => 2.76, 'quantity' => 3),
- array('group_id' => 14, 'team_price' => 4.99, 'satopay_price' => 4.60, 'team_id' => 335, 'origin' => 4.99, 'gain' => 0.31915, 'quantity' => 1),
- array('group_id' => 14, 'team_price' => 12.00, 'satopay_price' => 11.00, 'team_id' => 344, 'origin' => 24, 'gain' => 1.84, 'quantity' => 2),
- array('group_id' => 15, 'team_price' => 13.00, 'satopay_price' => 11.00, 'team_id' => 344, 'origin' => 24, 'gain' => 1.84, 'quantity' => 2),
- );
- $new_arr = array();
- foreach ($arr as $key => $value) {
- add_array($value, &$new_arr, 'group_id');
- }
- var_dump($new_arr);