对二维数组的每个子数组中的所有元素求和
我有以下二维数组,我想对每个子数组中的所有元素求和。
输入:
$main_array = [
[1, 2, 3],
[2, 4, 5],
[8, 4, 3]
]
期望的结果:
[6, 11, 15]
我尝试了以下代码:
foreach ($main_array as $key => $value)
$main_array[$key] = Array('1' => array_sum($value));
print_r($main_array);
但我得到的数组结构是:
Array
(
[0] => Array
(
[1] => 6
)
[1] => Array
(
[1] => 11
)
[2] => Array
(
[1] => 15
)
)
I've got the following 2d array and I want to sum all of the elements in each subarray.
Input:
$main_array = [
[1, 2, 3],
[2, 4, 5],
[8, 4, 3]
]
Desired Result:
[6, 11, 15]
I tried the following code:
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
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用 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
试试这个:
即将总和直接放在顶级数组中。
Try this:
That is, place the sum directly in the top level array.
对输入数组中的每一行调用
array_sum()
。array_map()
使此操作富有表现力、简洁,并且不需要声明任何新变量。代码:(演示)
输出:
Call
array_sum()
on every row in your input array.array_map()
makes this operation expressive, concise, and doesn't require any new variables to be declared.Code: (Demo)
Output: