[英]How to get sum of two dimensional array
我有两个数组
Array
(
[0] => Array
(
[0] => 7
[1] => 8
)
[1] => Array
(
[0] => 6
[1] => 3
)
)
Array
(
[0] => Array
(
[0] => 4
[1] => 7
)
[1] => Array
(
[0] => 8
[1] => 3
)
)
并希望将其在外部数组中的索引值求和为
Array
(
[0] => 13
[1] => 11
)
Array
(
[0] => 12
[1] => 10
)
为此我在做什么
$sum_inhale=array();
foreach($x_inhale as $k=>$sub_array)
{
foreach($sub_array as $id => $val)
{
$sum_inhale[$id] += $val; //<---Error occured here
}
}
print_r($sum_inhale);
但我也收到通知为什么?
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>A PHP Error was encountered</h4>
<p>Severity: Notice</p>
<p>Message: Undefined offset: 0</p>
<p>Filename: controllers/Report.php</p>
<p>Line Number: 463</p>
<p>Backtrace:</p>
<p style="margin-left:10px">
File: C:\xampp\htdocs\newyogapanel\application\controllers\Report.php<br />
Line: 463<br />
Function: _error_handler
</p>
<p style="margin-left:10px">
File: C:\xampp\htdocs\newyogapanel\index.php<br />
Line: 315<br />
Function: require_once
</p>
</div>
您可以将array_column()
与array_sum()
:
foreach($x_inhale as $ind => $ar){
$res[] = array_sum(array_column($x_inhale,$ind));
}
print_r($res);
$sum_inhale[$id]
在第一个循环中是空的,这就是你不能向它添加数字的原因。 在该行之前添加:
if (!isset($sum_inhale[$id])) $sum_inhale[$id] = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.