multidimensional array array_sum

后端 未结 10 1941
深忆病人
深忆病人 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

    Just a way to do it:

    $sum = 0;
    
    foreach($account_invoices as $num => $values) {
        $sum += $values[ 'vatAmount' ];
    }
    
    0 讨论(0)
  • 2020-11-27 07:00

    You could use array_map first to collect the vatAmout value.

    $sum = array_sum(array_map(function($var) {
      return $var['vatAmout'];
    }, $account_invoices));
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-27 07:02

    Also you can do this (if you like array_sum function):

    foreach($account_invoices as $num => $values) {
        $vatAmount[] = $values[ 'vatAmount' ];
    }
    
    $Total = array_sum($vatAmount);
    
    0 讨论(0)
  • 2020-11-27 07:04

    array_sum_multidimensional Helper function

    if (!function_exists('array_sum_multidimensional')) {
        /**
         * returns the sum of a element from an array of arrays
         */
    
        function array_sum_multidimensional(array $array, $elementKey){
    
            $sum = 0;
    
            foreach($array as $key => $value) {
                $sum += $value[ $elementKey ];
            }
    
            return $sum;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 07:08

    If you have PHP 5.5+ you can do this without looping or using a callback (since function calls are relatively expensive) ... just use:

    $sum = array_sum(array_column($account_invoices, 'vatAmount'));
    
    0 讨论(0)
提交回复
热议问题