MySQL/PHP SUM data in an ARRAY
I have the following query:
SELECT AVG (q1) AS q1, AVG (q2) AS q2, AVG (q3) AS q3
FROM thotels_results
WHERE brand IN ('ABC','EFG','XYZ')
AND date = 'NOV2010' GROUP BY brand;
I LOOP
through the results and have dumped out the array using var_dump
, the output is below:
array
'q1' => string '8.1724' (length=6)
'q2' => string '8.2414' (length=6)
'q3' => string '8.2414' (length=6)
array
'q1' => string '8.7714' (length=6)
'q2' => string '8.8429' (length=6)
'q3' => string '8.1643' (length=6)
array
'q1' => string '8.6009' (length=6)
'q2' => string '8.5686' (length=6)
'q3' => string '7.8528' (length=6)
What I would like to do is, somehow, add each of the q1's togethe开发者_运维百科r and divide by 3 to give me an average, then the same for q2 and the same for q3:
8.1724 + 8.7714 + 8.6009 / 3 = 8.5149
I'm not sure how to access the information stored in the array - thanks in advance.
Homer.
$q1Ave = $q2Ave = $q3Ave = 0
foreach ($results as $qValues) {
$q1Ave += $qValues['q1'];
$q2Ave += $qValues['q2'];
$q3Ave += $qValues['q3'];
}
$q1Ave /= count($results);
$q2Ave /= count($results);
$q3Ave /= count($results);
You can try
SELECT SUM(q1)/3 as q1, SUM(q2)/3 as q2, SUM(q3)/3 as q3
FROM (
SELECT AVG (q1) AS q1, AVG (q2) AS q2, AVG (q3) AS q3
FROM thotels_results
WHERE brand IN ('ABC','EFG','XYZ')
AND date = 'NOV2010' GROUP BY brand
) as derived_table;
before loop start
$q1sum=0;
$q2sum=0;
$q3sum=0;
$count=0
put this inside the loop you traversed.
$q1sum+=(float) $array['q1'] ;
$q2sum+=(float) $array['q2'] ;
$q3sum+=(float) $array['q3'] ;
$count++;
put this out of the loop after the loop end.
$q1final_result=$q1sum/$count;
$q2final_result=$q2sum/$count;
$q3final_result=$q3sum/$count;
$tab = array(
0 => array ("q1" => 2,"val2" => 5),
1 => array ("q1" => 6,"val2" => 10),
2 => array ("q1" => 15,"val2" => 50),
);
echo sum_subarrays_by_key( $tab, "q1" );
function sum_subarrays_by_key( $tab, $key ) {
$sum = 0;
foreach($tab as $sub_array) {
$sum += $sub_array[$key];
}
return $sum;
}
It will work at every depth of array. need to call by changing key which u want to sum in calling function
精彩评论