对二维数组的每个子数组中的所有元素求和

发布于 2024-12-10 07:30:31 字数 574 浏览 0 评论 0原文

我有以下二维数组,我想对每个子数组中的所有元素求和。

输入:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无悔心 2024-12-17 07:30:31

当您调用 Array 函数时,您显式地创建了一个数组,因此您必须将其从 Array('1'=>array_sum($value)); 中删除,

这就是您的代码的外观喜欢

foreach ($main_array as $key => $value)
  $main_array[$key] = 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);
¢好甜 2024-12-17 07:30:31

试试这个:

  foreach ($main_array as $key => $value)
     $main_array[$key] = array_sum($value);

即将总和直接放在顶级数组中。

Try this:

  foreach ($main_array as $key => $value)
     $main_array[$key] = array_sum($value);

That is, place the sum directly in the top level array.

念﹏祤嫣 2024-12-17 07:30:31

对输入数组中的每一行调用 array_sum()array_map() 使此操作富有表现力、简洁,并且不需要声明任何新变量。

代码:(演示)

$array = [
    [1, 2, 3],
    [2, 4, 5],
    [8, 4, 3],
];

var_export(array_map('array_sum', $array));

输出:

array (
  0 => 6,
  1 => 11,
  2 => 15,
)

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)

$array = [
    [1, 2, 3],
    [2, 4, 5],
    [8, 4, 3],
];

var_export(array_map('array_sum', $array));

Output:

array (
  0 => 6,
  1 => 11,
  2 => 15,
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文