6

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 entries 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 sophisticated solution for my problem or do I have to take the long road and do every step manually?

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

(Alternatively you also could just use array_reduce, if you think this would be more elegant; but that here actually does the job too.)
@ bwoebi: much obliged! works like a charm - with a small alteration for my logic (negate if-clause): code if (!isset($result[$val['mitarbeiter_id']])) code otherwise it would not sum up the income.
0

This should work:

$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

5 Comments

actually, you'd first need to create an array where the keys are setid…
I modified answer so you don't have to
Hehe, now it just nearly looks like my answer :-)
Yeah it would have worked the way before however it just throws a notice.
This doesn't create the desired structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.