我该如何添加这些数组?

时间:2013-05-13 01:41:05

标签: php

如何添加所有数组的total_qty_ordered?

这可以是任意数量的数组

       Array ( [0] => Array ( [total_qty_ordered] => 1.0000 [1] => ) [1] => Array
     ( [total_qty_ordered] => 1.0000 [1] => ) [2] => Array ( [total_qty_ordered] => 1.0000
 [1] =>
     ) [3] => Array ( [total_qty_ordered] => 1.0000 [1] => ) [4] => Array ( 
[total_qty_ordered] =>
     1.0000 [1] => ) [5] => Array ( [total_qty_ordered] => 1.0000 [1] => ) [6] => Array (

    [total_qty_ordered] => 1.0000 [1] => ) [7] => Array ( [total_qty_ordered] => 1.0000 [1]
 => )
     [8] => Array ( [total_qty_ordered] => 1.0000 [1] => ) [9] => Array ( 
[total_qty_ordered] => 
    2.0000 [1] => ) [10] => Array ( [total_qty_ordered] => 1.0000 [1] => ) [11] => Array (
 [total_qty_ordered] => 1.0000 [1] => ) )

2 个答案:

答案 0 :(得分:2)

$sum = array_sum(array_map(function($item){
  return $item['total_qty_ordered'];
}, $array));

但是如果您的数组结构确实如此(第二个值真的是空的),您也可以这样做:

$sum = array_sum(call_user_func_array('array_merge',
            array_map('array_values', $array)));

答案 1 :(得分:0)

在PHP 5.5中,你可以这样做:

 $sum = array_sum(array_col('total_qty_ordered', $array));