从多维数组中求和并合并重复值

时间:2018-01-02 09:12:07

标签: php arrays multidimensional-array

我想将movements的值加总,同时在同一个数组上保留day的唯一值。

基础数组:

array (607)
0 => array (2)
    day => "11" (2)
    movements => 1
1 => array (2)
    day => "11" (2)
    movements => 1
2 => array (2)
    day => "11" (2)
    movements => 1
3 => array (2)
    day => "12" (2)
    movements => 1
4 => array (2)
    day => "12" (2)
    movements => 1
5 => array (2)
    day => "12" (2)
    movements => 1

[...]

我期待的结果(对于每个day总和movements):

array (607)
    0 => array (2)
        day => "11" (2)
        movements => 3
    1 => array (2)
        day => "12" (2)
        movements => 3    
    [...]

非常感谢任何帮助。

编辑:到目前为止我尝试了什么:

  • docs of QMainWindow:它还总结day,这不是我所期待的。
  • 我自己的代码:

    $arr1 = $stats['data']['vhc']; // contain ['day'] and ['movements']
    $arr2 = $data['vhc']; // contain ['day'] and ['movements']
    $sum = [];
    
    if (!empty($arr1)) {
        $result = [];
        foreach ($arr1 as $key => $value) {
            if (isset($arr2[$key]['day']) && $arr2[$key]['day'] == $value['day']) {
                $result['day'] = $value['day'];
                $result['movements'] = $value['movements'] + $arr2[$key]['movements'];
            }
            array_push($sum, $result);
        }
    }
    

2 个答案:

答案 0 :(得分:1)

您可以轻松使用foreach()https://developers.google.com/analytics/devguides/collection/gtagjs/cross-domain

$final_array = [];

foreach($array as $arr){
  $final_array[$arr['day']]['day'] = $arr['day'];
  $final_array[$arr['day']]['movements'] = (isset($final_array[$arr['day']]['movements']))? $final_array[$arr['day']]['movements']+$arr['movements'] : $arr['movements'];    
}
$final_array = array_values($final_array);

print_r($final_array);

输出: - array_values()

答案 1 :(得分:1)

此方法不会用相同的值覆盖结果数组数据。

代码:(Demo

$array=[
    ['day'=>'11','movements'=>'1'],
    ['day'=>'11','movements'=>'1'],
    ['day'=>'11','movements'=>'1'],
    ['day'=>'12','movements'=>'1'],
    ['day'=>'12','movements'=>'1'],
    ['day'=>'12','movements'=>'1']
];
foreach($array as $row){  // iterate all rows
    if(!isset($result[$row['day']])){  // if first occurrence of day...
        $result[$row['day']]=$row;     // save the full row with day as the temporary key
    }else{                                    // if not the first occurrence of day...
        $result[$row['day']]['movements']+=$row['movements'];  // add movements value
    }
}
var_export(array_values($result));

输出:

array (
  0 => 
  array (
    'day' => '11',
    'movements' => 3,
  ),
  1 => 
  array (
    'day' => '12',
    'movements' => 3,
  ),
)