How to sum all column values in multi-dimensional array?

后端 未结 20 2513
花落未央
花落未央 2020-11-22 00:57

How can I add all the columnar values by associative key? Note that key sets are dynamic.

Input array:

Arr         


        
相关标签:
20条回答
  • 2020-11-22 01:33

    It can also be done using array_walk:

    function array_sum_values(array $input, $key) {
       $sum = 0;
       array_walk($input, function($item, $index, $params) {
             if (!empty($item[$params[1]]))
                $params[0] += $item[$params[1]];
          }, array(&$sum, $key)
       );
       return $sum;
    }
    
    var_dump(array_sum_values($arr, 'gozhi'));
    

    Not so readable like previous solutions but it works :)

    0 讨论(0)
  • 2020-11-22 01:33

    Here's a version where the array keys may not be the same for both arrays, but you want them all to be there in the final array.

    function array_add_by_key( $array1, $array2 ) {
        foreach ( $array2 as $k => $a ) {
            if ( array_key_exists( $k, $array1 ) ) {
                $array1[$k] += $a;
            } else {
                $array1[$k] = $a;
            }
        }
        return $array1;
    }
    
    0 讨论(0)
  • 2020-11-22 01:35
        $resultat = array();
    
    foreach ($myArray as $myArray_key => $myArray_data) {
        foreach ($myArray_data as $key => $data) {
            $resultat[$key] += $data;
        }
    }
    
    print_r($resultat);
    
    0 讨论(0)
  • 2020-11-22 01:38

    You can use array_walk_recursive() to get a general-case solution for your problem (the one when each inner array can possibly have unique keys).

    $final = array();
    
    array_walk_recursive($input, function($item, $key) use (&$final){
        $final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
    });
    

    Example with array_walk_recursive() for the general case

    Also, since PHP 5.5 you can use the array_column() function to achieve the result you want for the exact key, [gozhi], for example :

    array_sum(array_column($input, 'gozhi')); 
    

    Example with array_column() for the specified key

    If you want to get the total sum of all inner arrays with the same keys (the desired result that you've posted), you can do something like this (bearing in mind that the first inner array must have the same structure as the others) :

    $final = array_shift($input);
    
    foreach ($final as $key => &$value){
       $value += array_sum(array_column($input, $key));
    }    
    
    unset($value);
    

    Example with array_column() in case all inner arrays have the same keys

    If you want a general-case solution using array_column() then at first you may consider to get all unique keys , and then get the sum for each key :

    $final = array();
    
    foreach($input as $value)
        $final = array_merge($final, $value);
    
    foreach($final as $key => &$value)
        $value = array_sum(array_column($input, $key));
    
    unset($value);
    

    Example with array_column() for the general case

    0 讨论(0)
  • 2020-11-22 01:39

    Another version, with some benefits below.

    $sum = ArrayHelper::copyKeys($arr[0]);
    
    foreach ($arr as $item) {
        ArrayHelper::addArrays($sum, $item);
    }
    
    
    class ArrayHelper {
    
        public function addArrays(Array &$to, Array $from) {
            foreach ($from as $key=>$value) {
                $to[$key] += $value;
            }
        }
    
        public function copyKeys(Array $from, $init=0) {
            return array_fill_keys(array_keys($from), $init);
        }
    
    }
    

    I wanted to combine the best of Gumbo's, Graviton's, and Chris J's answer with the following goals so I could use this in my app:

    a) Initialize the 'sum' array keys outside of the loop (Gumbo). Should help with performance on very large arrays (not tested yet!). Eliminates notices.

    b) Main logic is easy to understand without hitting the manuals. (Graviton, Chris J).

    c) Solve the more general problem of adding the values of any two arrays with the same keys and make it less dependent on the sub-array structure.

    Unlike Gumbo's solution, you could reuse this in cases where the values are not in sub arrays. Imagine in the example below that $arr1 and $arr2 are not hard-coded, but are being returned as the result of calling a function inside a loop.

    $arr1 = array(
        'gozhi' => 2,
        'uzorong' => 1,
        'ngangla' => 4,
        'langthel' => 5
    );
    
    $arr2 = array(
       'gozhi' => 5,
       'uzorong' => 0,
       'ngangla' => 3,
       'langthel' => 2
    );
    
    $sum = ArrayHelper::copyKeys($arr1);
    
    ArrayHelper::addArrays($sum, $arr1);
    ArrayHelper::addArrays($sum, $arr2);
    
    0 讨论(0)
  • 2020-11-22 01:39

    For example, you can pluck all fields from a result like this below.

    I am picking out the 'balance' from an array and save to a variable

    $kii =   $user->pluck('balance');
    

    then on the next line u can sum like this:

    $sum =  $kii->sum(); 
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题