i have already function that SUM sub arrays which has matches keys like this
$totals = array();
$count_loops = 0 ;
// First get our totals.
foreach ($average as $subKey => $subArray) {
foreach ($subArray as $k => $v) {
// Add the column to our total.
$totals[$k] = isset($totals[$k] ) ? $totals[$k] + $v / $count_loops : $v;
}
}
and return total array like this
Array
(
[john_total] => 519.44
[adam_total] => 1664.64
[sara_total] => 1237.53
}
but i want to return average after sum bu divide sum number with count loops,but it return wrong average..if i delete this code / $count_loops
it sum good..so how to do this
Think you can use : array_sum and count function in PHP :
$totals = array();
$count_loops = 0 ;
// First get our totals.
foreach ($average as $subKey => $subArray) {
$totals[$k] = array_sum($subArray) / count($subArray);
}
By using array_sum
and count
array_sum will give you sum of total result.
and count will give you total number of element.
and average is A calculated "central" value of a set of numbers.
so
$average = array_sum($array) / count($array);
Be mindful of the calculation which is going to happen at this point of your code.
$totals[$k] = isset($totals[$k] ) ? $totals[$k] + $v / $count_loops : $v;
I'd rather you have it as
$totals[$k] = isset($totals[$k] ) ? ( $totals[$k] + $v ) / $count_loops : $v;
( 5 + 2.5 ) / 2 => 7.5 / 2 = 3.75
5 + ( 2.5 / 2 ) => 5 + 1.25 = 6.25
Those calculations are same figures but dependent on operator precedence. See http://php.net/manual/en/language.operators.precedence.php