Find the sum of elements by column in PHP

Kaleem Nalband :

I have this multi-dimensional array:

$dataset = [
[5,15,25],
[15,5,27],
[10,8,16]
]

My problems are:

  1. the data set can have any number of arrays but each array in data set will have the same number of elements

  2. I want to write a function that will return an array, which contains totals of elements at same index, i.e. total of all the first array elements and total of all the second elements and so on... in "$total" array

Example:

function find_total($dataset){
  $total[0]=5+15+10 //total of all the first elements
  $total[1]=15+5+8 //total of all the second elements
  $total[2]=25+27+16 //total of all the third elements

  return $total;
}
ainasma :
   function getArraySUm($dataset){
        $total = array();
        for($i=0; $i<count($dataset); $i++){
            $subArray = $dataset[$i];
            for($j=0; $j<count($subArray); $j++){
                if(!isset($total[$i])) $total[$i] = 0;
                $total[$j]+=$subArray[$j];
            }
        }
        return $total;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=198080&siteId=1