Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array find duplicates, sum them up & delete duplicates

i have an array:

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

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

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

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?

thanks and greetings

like image 350
Stefan Avatar asked Oct 02 '22 17:10

Stefan


1 Answers

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
like image 197
bwoebi Avatar answered Oct 07 '22 20:10

bwoebi