Get average from array
It looks like I can get the average of the whole array but not of each item in a array. I would like to avoid some loop. I use the function AVG() for it.
$sql_statement = "SELECT AVG(answer) AS averageanswer
FROM answer2
WHERE question_id
IN(".implode(",", $qid).")
AND answer <= 5
";
$dblink = mysql_connect($DBhost, $DBuser, $DBpassword);
mysql_select_db($DB,$dblink);
$qry = mysql_query($sql_statement,$dblink);
while($averageanswer=mysql_fetch_array($qry)) {
$average[] = round($average开发者_开发问答answer['averageanswer']);
}
When I print the array this is the result:
Array ( [0] => 4 )
Did someone experience the same problem before or does someone know the solution for me? All tips are welcome!
I presume you are wanting the Average results, per question. In which case:
$sql_statement = "SELECT AVG(answer) AS averageanswer
FROM answer2
WHERE question_id
IN(".implode(",", $qid).")
AND answer <= 5
GROUP BY question_id
";
$dblink = mysql_connect($DBhost, $DBuser, $DBpassword);
mysql_select_db($DB,$dblink);
$qry = mysql_query($sql_statement,$dblink);
while($averageanswer=mysql_fetch_array($qry)) {
$average[] = round($averageanswer['averageanswer']);
}
This will result in one row, per question_id, containing the average of answers for any row with that question_id
精彩评论