我有一个2维数组,由函数传递的内容如下所示
function crash_reporter($evaluation){
foreach ($evaluation as $agent){
unset($agent['time']);
print_r($agent);
}
比我得到以下数组而且我很难得到索引值的总和。
Array
(
[agent_example1] => 0
[agent_example2] => 2
[agent_example3] => 0
[agent_example4] => 1
[] => 0
)
Array
(
[agent_example1] => 0
[agent_example2] => 1
[agent_example3] => 0
[agent_example4] => 0
[] => 0
)
Array
(
[agent_example1] => 0
[agent_example2] => 3
[agent_example3] => 0
[agent_example4] => 0
[] => 0
)
)
)
result should be int. 7
答案 0 :(得分:2)
你可能想尝试这样的事情:
function sum_2d_array($outer_array) {
$sum = 0;
foreach ($outer_array as $inner_array) {
foreach ($inner_array as $number) {
$sum += $number;
}
}
return $sum;
}
答案 1 :(得分:1)
甚至更容易:
function crash_reporter($evaluation){
$sum = 0;
foreach ($evaluation as $agent){
unset($agent['time']);
$sum += array_sum($agent);
}
echo $sum;
}
答案 2 :(得分:0)
您可以在$agent
循环之后将每个子数组(foreach/unset
)的总和相加,如:
$sum = array_sum(array_map('array_sum', $evaluation));