从阵列获得平均值

时间:2011-04-24 11:28:10

标签: php sql average

看起来我可以获得整个数组的平均值,但不能得到数组中每个项目的平均值。我想避免一些循环。 我使用函数AVG()。

$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($averageanswer['averageanswer']);
}

当我打印数组时,结果如下:

Array ( [0] => 4 )

之前有人遇到过同样的问题或有人知道我的解决方案吗?欢迎所有提示!

1 个答案:

答案 0 :(得分:4)

我认为你想要平均结果,每个问题。在这种情况下:

$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']);
}

这会产生一行,每个question_id,包含具有该question_id的任何行的答案的平均值