我有以下数组作为 $main_array .想要对子数组中的所有元素求和,例如 [0]=>6, [1]=>11, [2]=>15.>
I've got the following array as $main_array .Wanted to sum up all the elements in the sub array such as [0]=>6, [1]=>11, [2]=>15.
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 2
[1] => 4
[2] => 5
)
[2] => Array
(
[0] => 8
[1] => 4
[2] => 3
)
)
尝试了以下代码.
foreach ($main_array as $key => $value)
$main_array[$key] = Array('1'=>array_sum($value));
print_r($main_array);
但是我得到的数组结构是,
But the array structure I got was,
Array
(
[0] => Array
(
[1] => 6
)
[1] => Array
(
[1] => 11
)
[2] => Array
(
[1] => 15
)
)
我期待数组结构如下.
Array
(
[0] => 6
[1] => 11
[2] => 15
)
提前致谢!
当你调用 Array 函数时,你明确地创建了一个数组,所以你必须从 Array('1'=>array_sum($value));
When you're calling Array function you're explicitly making an array so you have to remove this from Array('1'=>array_sum($value));
这就是你的代码应该是什么样子
This is how your code should look like
foreach ($main_array as $key => $value)
$main_array[$key] = array_sum($value);
这篇关于子数组中所有元素的总和 - PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!