Reputation: 115
I'm not sure how to formulate the title of my question. I have this array:
Array
(
[0] => Array
(
[account] => 700000
[percent] => 0.0000
[amount] => 3
)
[1] => Array
(
[account] => 705010
[percent] => 6.0000
[amount] => 4.7
)
[2] => Array
(
[account] => 700000
[percent] => 0.0000
[amount] => 93
)
[3] => Array
(
[account] => 700000
[percent] => 6.0000
[amount] => 9.43
)
[4] => Array
(
[account] => 700000
[percent] => 12.0000
[amount] => 35.72
)
[5] => Array
(
[account] => 700000
[percent] => 21.0000
[amount] => 8.26
)
[6] => Array
(
[account] => 705300
[percent] => 21.0000
[amount] => 8.26
)
[7] => Array
(
[account] => 705300
[percent] => 21.0000
[amount] => 57.86
)
)
I need to find a way to add up the amount if both account and percent match.
Should I loop over each array and do "if" checks to see if the account and percent already exist, then add up amount, else leave it as it is?
Is there a php function for this?
I have been looking into array_unique but I'm not quite sure how to do it like that.
As always, any help is appreciated!
Upvotes: 0
Views: 375
Reputation: 41810
You could use something like this. It will generate a nested structure that seems like it would probably be easier to work with.
foreach ($array as $item) {
$grouped[$item['account']][$item['percent']] += $item['amount'];
}
If you need to put them back into the original format, just do basically the opposite operation
foreach ($grouped as $account => $percents) {
foreach ($percents as $percent => $amount) {
$new_array[] = array(
'account' => $account, 'percent' => $percent, 'amount' => $amount);
}
}
Upvotes: 1