如何求和多维数组的所有关联值?

时间:2014-02-06 20:20:28

标签: php arrays multidimensional-array associative-array array-sum

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

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))

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

答案 2 :(得分:0)

有几种方法可以成功地求和:

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

Demo of all approaches

纯粹基于函数的方法:

// 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


p.s。假设每个子数组中都有唯一的用户标识符,则可以将这些子数组与“ splat运算符”合并以生成一维数组,这将设置array_sum()的使用。 (Demo

echo array_sum(array_merge(...$array));
// 60