搜索重复项(如果找到总和值)

时间:2019-03-21 12:49:54

标签: php php-7

我有这个数组:

$data = [
    0 => [
       'date'       => '2018-09-12',
       'department' => 12,
       'country'    => 14,
       'total'      => 12
    ],
    1 => [
       'date'       => '2018-09-12',
       'department' => 12,
       'country'    => 14,
       'total'      => 18
    ],
    2 => [
       'date'       => '2018-09-12',
       'department' => 12,
       'country'    => 15,
       'total'      => 10
    ]
];

返回应为:

$return = [
   0 => [
       'date'       => '2018-09-12',
       'department' => 12,
       'country'    => 14,
       'total'      => 30
   ],
   1 => [
       'date'       => '2018-09-12',
       'department' => 12,
       'country'    => 15,
       'total'      => 10
   ]
];

我尝试过这样:

foreach ($data as $value) {
     if(!in_array($value, $data)) {
         $result[] = $data;
     }
}

这个想法是,如果除total以外的所有字段都是相同的,则将total添加到具有相同字段的现有total中。请帮我。提前谢谢,对不起我的英语

2 个答案:

答案 0 :(得分:4)

您可以通过遍历数组,将每个元素的所有其他值(datedepartmentcountry)与以前看到的值进行比较,然后在将总和求和时进行此操作进行比赛。这段代码使用serialize生成其他值的组合键进行比较:

$output = array();
$keys = array();
foreach ($data as $value) {
    $total = $value['total'];
    unset($value['total']);
    $key = serialize($value);
    if (($k = array_search($key, $keys)) !== false) {
        $output[$k]['total'] += $total;
    }
    else {
        $keys[] = $key;
        $output[] = array_merge($value, array('total' => $total));
    }
}
print_r($output);

输出:

Array (
    [0] => Array (
        [date] => 2018-09-12
        [department] => 12
        [country] => 14
        [total] => 30 
    )
    [1] => Array (
        [date] => 2018-09-12
        [department] => 12
        [country] => 15
        [total] => 10
     ) 
)

Demo on 3v4l.org

通过使用复合键作为$output数组的索引,我们可以简化此代码,我们只需要在循环后使用array_values来重新索引$output数组:

$output = array();
foreach ($data as $value) {
    $v = $value;
    unset($v['total']);
    $key = serialize($v);
    if (isset($output[$key])) {
        $output[$key]['total'] += $value['total'];
    }
    else {
        $output[$key] = $value;
    }
}
$output = array_values($output);
print_r($output);

输出与以前相同。 Demo on 3v4l.org

答案 1 :(得分:0)

您也可以尝试此方法,因为它不需要太多的内存密集型操作(例如合并),尤其是在处理大量数据时:

$new_data=[];
foreach($data as $key=>$value){
    $i=array_search($value["date"],array_column($new_data,"date"));
    if(($i!==false)&&($new_data[$i]["department"]==$value["department"])&&($new_data[$i]["country"]==$value["country"])){
        $new_data[$i]["total"]+=$value["total"];
    }
    else{
        $new_data[]=$value;
    }
}
print_r($new_data);