Search code examples
phpsumarray-column

Sum a column of data in a 2d array


How can I get the addition of the total_qty_ordered of all the arrays?

This can be any number of arrays

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

Solution

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

    But if your array structure is really that (2nd value is really empty), you can also do:

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