PHP数组查找重复,总结他们向上和删除重复 [英] php array find duplicates, sum them up & delete duplicates

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

问题描述

我有一个数组:

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

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

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

我需要找到具有相同SETID entrys,总结他们的收入和删除重复entrys - 到底应该是这样的:

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
    )
)

没有人知道我的问题sophosticated溶液或做我必须走漫长的道路,并手动执行每一步?

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

感谢和问候

推荐答案

只要创建一个新的阵列,您可以通过使用SETID为重点进行快速adressable。并重新索引末尾的数组。

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数组查找重复,总结他们向上和删除重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆