如果找到总和值,则搜索重复项 [英] Search for duplicates, if found sum values
问题描述
我有这个数组:
$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;
}
}
这个想法是,如果除总计之外的所有字段都相同,则将总计添加到具有相同字段的现有总计中.请帮我.提前感谢并为我的英语感到抱歉
The idea is, if all fields except total are indentical, then add total to the existing total with the same fields. Please help me. Thx in advance and sorry for my english
推荐答案
您可以通过循环遍历数组,比较每个元素的所有其他值(date
, department
和 country
) 与之前看到的值,并在匹配时求和.此代码使用 serialize
生成复合键用于比较的其他值:
You can do this by looping through your array, comparing all the other values of each element (date
, department
and country
) with previously seen values and summing the totals when you get a match. This code uses serialize
to generate a composite key of the other values for comparison:
$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
)
)
通过使用复合键作为$output
数组的索引,我们可以简化这段代码,我们只需要使用array_values
在循环之后重新索引 $output
数组:>
By using the composite key as the index into the $output
array, we can simplify this code, we just need to use array_values
after the loop to re-index the $output
array:
$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);
输出和以前一样.3v4l.org 上的演示
这篇关于如果找到总和值,则搜索重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!