我有一个这样的数组:
array(5) {
["Uniform"]=>
array(2) {
[0]=>
array(2) {
["invoice_pname"]=>
string(7) "Uniform"
["amount"]=>
string(3) "900"
}
[1]=>
array(2) {
["invoice_pname"]=>
string(7) "Uniform"
["amount"]=>
string(3) "450"
}
}
["Tuition Fee"]=>
array(2) {
[0]=>
array(2) {
["invoice_pname"]=>
string(11) "Tuition Fee"
["amount"]=>
string(3) "300"
}
[1]=>
array(2) {
["invoice_pname"]=>
string(11) "Tuition Fee"
["amount"]=>
string(3) "300"
}
}
}
我想在关键元素中添加数组值,例如:
Uniform => 1350
学费=> 600
我所做的是使用foreach
作为循环,
$results = array();
foreach ($result as $key => $resultant) {
foreach ($resultant as $value) {
$results[$key][] += $value['amount'];
}
}
var_dump($results);
但它显示错误
<h4>A PHP Error was encountered</h4>
<p>Severity: Notice</p>
<p>Message: Undefined index: Uniform</p>
<p>Filename: controllers/Home.php</p>
<p>Line Number: 2787</p>
<p>Backtrace:</p>
任何人都可以帮助我吗?我想把它放在一张桌子里。
答案 0 :(得分:0)
查看您的数据,您应该迭代结果[&#39; Uniform&#39;]
$results = array();
foreach ($result['Uniform'] as $key => $resultant) {
foreach ($resultant as $value) {
$results[$key][] += $value['amount'];
}
}
因为看起来这个键是包含sum
的有效数组的键答案 1 :(得分:0)
您可以使用array_column和array_sum 这样你就不需要循环整个数组了。
Foreach($arr as $key => $a){
$res[$key] = array_sum(array_column($a, "amount"));
}
Var_dump($res);