0

如何对这个关联数组的所有值求和:

Array ( 
    [0] => Array ( [user1] => 20 ) 
    [1] => Array ( [user2] => 30 ) 
    [3] => Array ( [user3] => 10 ) 
) 

预期输出:

60

我试过了,array_sum没有用:

$lsd = Array ( [0] => Array ( [user1] => 20 ) [1] => Array ( [user2] => 30 ) [3] => Array ( [user3] => 10 ) ) 

print_r(array_sum($lsd))

过去 2 小时我一直在搜索 stackoverflow,但没有找到任何东西。

4

3 回答 3

3
$array = Array ( 
 0 => Array ( "user1" => 20 ), 
 1 => Array ( "user2" => 30 ),
 3 => Array ( "user3" => 10 ) 
); 

$new=0;

foreach($array as $value){
 foreach($value as $value1){
  $new += $value1;
 }  
}
echo $new;

输出

60

于 2014-02-06T20:27:35.473 回答
0
$lsd = array ( array ('user1' => 20 ), array ('user2' => 30 ), array ('user3' => 10 ));

$sum = array_reduce(
    $lsd,
    function($sum, $value) {
        $sum += array_pop($value);
        return $sum;
    },
    0
);

var_dump($sum);
于 2014-02-06T20:29:45.560 回答
0

有几种方法可以成功地对这些值求和:

使用:$array = [['user1' => 20], ['user2' => 30], 3 => ['user3' => 10]];

所有方法的演示

纯粹的基于函数的方法:

// reindex subarrays, isolate zero column, sum values
echo array_sum(array_column(array_map('array_values', $array), 0));

递归方法(简洁,但可以说是“矫枉过正”):

// visit each leafnode, increase the $sum ("modifiable" via &) tally
array_walk_recursive($array, function($v)use(&$sum){ $sum += $v; });
echo $sum;

一种语言构造方法(纯 foreach 循环):

$total = 0;  // without this declaration, you will generate: "Notice: Undefined variable"
foreach ($array as $subarray) {  // iterate outer array
    foreach ($subarray as $v) {  // iterate each inner array
        $total += $v;            // increase $total
    }
}
echo $total;

以上所有解决方案都将输出60.


ps 假设您在每个子数组中都有唯一的用户标识符,您可以将子数组与“splat 运算符”合并以生成一维数组,这将设置使用array_sum(). (演示

echo array_sum(array_merge(...$array));
// 60
于 2018-09-05T04:24:15.647 回答