我不确定如何制定问题的标题。 我有这个数组:
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
)
)
如果帐户和百分比都匹配,我需要找到一种方法来累加金额。
我应该遍历每个数组并执行“if”检查以查看帐户和百分比是否已经存在,然后加上金额,否则保持原样?
这是否有php功能?
我一直在研究array_unique,但我不太确定如何做到这一点。
一如既往,感谢任何帮助!
答案 0 :(得分:1)
你可以使用这样的东西。它将生成一个嵌套结构,似乎可能更容易使用。
foreach ($array as $item) {
$grouped[$item['account']][$item['percent']] += $item['amount'];
}
如果你需要把它们放回原来的格式,那就基本上做相反的操作
foreach ($grouped as $account => $percents) {
foreach ($percents as $percent => $amount) {
$new_array[] = array(
'account' => $account, 'percent' => $percent, 'amount' => $amount);
}
}