"accounts" => array:6 [
0 => array:2 [
"acc_id" => 1
"balance" => 1000.00
]
1 => array:2 [
"acc_id" => 2
"balance" => -1500.00
]
2 => array:4 [
"acc_id" => 3
"balance" => 5000.00
]
]
嗨,我该如何总结所有正确的余额?
代码
foreach ($y['accounts'] as $k)
{
$sum_balance = $k['balance'];
}
$sum_balance += $sum_balance;
使用此代码,结果将只累加最后一个余额本身。示例结果为10000.00
答案 0 :(得分:3)
您需要在foreach循环中增加总和:
$sum_balance = 0;
foreach ($y['accounts'] as $k)
{
$sum_balance += $k['balance'];
}
var_dump($sum_balance);
答案 1 :(得分:3)
将array_sum()
与array_column()
组合
array_column()
从输入数组的单个列中返回值
array_sum()
计算数组中的值之和
$y = [
'accounts' => [
0 => [
"acc_id" => 1,
"balance" => 1000.00
],
1 => [
"acc_id" => 2,
"balance" => -1500.00
],
2 => [
"acc_id" => 3,
"balance" => 5000.00
]
]
];
var_dump(
array_sum(array_column($y['accounts'], 'balance'))
);
float 4500
答案 2 :(得分:1)
您的解决方案几乎是正确的,只需在循环之前初始化$sum_balance
并在循环内求和。
$sum_balance=0;
foreach ($y['accounts'] as $k)
{
$sum_balance += $k['balance'];
}
希望它会有所帮助,如果您需要任何帮助,请随时联系。