php 数组查找重复项,汇总它们并删除重复项


php array find duplicates, sum them up & delete duplicates

我有一个数组:

Array 
(
[0] => Array
    (
        [setid] => 2
        [income] => 100
    )
[1] => Array
    (
        [setid] => 2
        [income] => 120
    )
[2] => Array
    (
        [setid] => 3
        [income] => 700
    )
)

我需要找到具有相同 setid 的条目,汇总他们的收入并删除重复的条目 - 最后它应该看起来像这样:

Array
(
[0] => Array
    (
        [setid] => 2
        [income] => 220
    )
[1] => Array
    (
        [setid] => 3
        [income] => 700
    )
)

是否有人知道我的问题的解决方案,或者我是否必须走很长的路并手动完成每一步?

感谢和问候

只需创建一个新数组,通过使用 setid 作为键使其可快速解决。并在最后重新索引数组。

$result = array();
foreach ($array as $val) {
    if (!isset($result[$val['setid']]))
        $result[$val['setid']] = $val;
    else
        $result[$val['setid']]['income'] += $val['income'];
}
$result = array_values($result); // reindex array

这应该有效:

$values = array();
foreach($array as $val) {
    if(isset($values[$val['setid']])) {
        $values[$val['setid']] += $val['income'];
    } else {
        $values[$val['setid']] = $val['income'];
    }
}
//all values are now in $values array, keys are setid and values are income

编写自己的函数,这根本不是漫长的道路。

$result = array_reduce($originalArray, function($memo, $item){
  isset($memo[$item['setid']])
    ? $memo[$item['setid']] = $item['income']
    : $memo[$item['setid']] += $item['income'];
  return $memo;
}, []);

你应该使用 php 官方网站提供的array_unique函数。

举个例子:

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

输出:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

要对重复的值求和,您可以使用 array_count_values 函数:

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

输出将是:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)