multidimensional array array_sum

后端 未结 10 2012
深忆病人
深忆病人 2020-11-27 06:45

I have seen various posted about this question so am aware some answers to this may exist. however I am none the wiser after reading these.

I have an array that is

10条回答
  •  余生分开走
    2020-11-27 07:00

    You can't do this directly with array_sum, which would sum everything in the array.

    You can do it with a loop:

    $sum = 0;
    foreach($items as $item)
        $sum += $item['vatAmount'];
    

    or you can filter the array (in this case it isn't very convenient, but if you had to calculate, say, S&H expenses plus VAT plus..., from each single item, and then sum...):

    // Input: an array (element #n of array of arrays), output: VAT field
    function getVAT($item)
    {
        return $item['vatAmount'];
    }
    
    // Array with all VATs
    $vats = array_map('getVAT', $items);
    
    $sum = array_sum($vats);
    

提交回复
热议问题