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

后端 未结 20 2517
花落未央
花落未央 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:21

    Here you have how I usually do this kind of operations.

    // We declare an empty array in wich we will store the results
    $sumArray = array();
    
    // We loop through all the key-value pairs in $myArray
    foreach ($myArray as $k=>$subArray) {
    
       // Each value is an array, we loop through it
       foreach ($subArray as $id=>$value) {
    
           // If $sumArray has not $id as key we initialize it to zero  
           if(!isset($sumArray[$id])){
               $sumArray[$id] = 0;
           }
    
           // If the array already has a key named $id, we increment its value
           $sumArray[$id]+=$value;
        }
     }
    
     print_r($sumArray);
    

提交回复
热议问题