本文介绍了php数组查找重复项,总结它们&删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

Array
(
[0] => Array
    (
        [setid] => 2
        [income] => 100
    )

[1] => Array
    (
        [setid] => 2
        [income] => 120
    )

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

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

i need to find entrys with the same setid, sum their income up and delete duplicate entrys - in the end it should look like this:

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

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

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

does someone know a sophosticated solution for my problem or do i have to take the long road and do every step manually?

感谢和问候

推荐答案

只需创建一个新数组,您可以使用 setid 作为键快速寻址该数组.并在最后重新索引数组.

Just create a new array which you make fast adressable by using the setid as key. And reindex the array at the end.

$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

这篇关于php数组查找重复项,总结它们&删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:57