你好,我正在开发一个评分系统,它将显示所有用户的所有评分,并使用PHPfromMySQL进行总结。结果运行良好,计算也正常(计算是用php进行的,而不是用MySQL进行的)。现在我的问题是,我怎样才能把总分从高到低排序。
代码如下:

$sel_query="Select * from tbl_scores";
$result = mysql_query($sel_query);
while($row = mysql_fetch_array($result)) {
$crit_3 = $row["crit_3"];
$crit_3a = number_format($crit_3);

$crit2_3 = $row["crit2_3"];
$crit2_3a = number_format($crit2_3);

$crit3_3 = $row["crit3_3"];
$crit3_3a = number_format($crit3_3);

$user1 = ($crit_3) ;
$user2 = ($crit2_3);
$user3 = ($crit3_3);
$divide = ($user1 + $user2 + $user3);
$total = number_format($divide / 9  , 2, '.', '');
$average = number_format($total * 0.15 , 2, '.', '');
?>

提前谢谢。

最佳答案

1.请停止使用(从php7中删除的php5.5+不推荐使用)mysql_*,使用mysqli_*PDO
2.在循环外定义一个数组变量,在循环内为该数组分配总分。
3.现在您将得到一个分数数组,现在您可以使用rshort()方法来正确获取数据。
所以代码应该如下:-

$sel_query="Select * from tbl_scores";
$result = mysql_query($sel_query);
$scores_array = array();//create an array
while($row = mysql_fetch_array($result)) {
$crit_3 = $row["crit_3"];
$crit_3a = number_format($crit_3);

$crit2_3 = $row["crit2_3"];
$crit2_3a = number_format($crit2_3);

$crit3_3 = $row["crit3_3"];
$crit3_3a = number_format($crit3_3);

$user1 = ($crit_3) ;
$user2 = ($crit2_3);
$user3 = ($crit3_3);
$divide = ($user1 + $user2 + $user3);
$total = number_format($divide / 9  , 2, '.', '');
$average = number_format($total * 0.15 , 2, '.', '');
$scores_array[$row['user_name']] = $total; // assign total to the array and i assume that your table has one column name user_name for each user, change accordingly
}
rsort($scores_array);// sort the array in decending order of total scores
foreach ($scores_array as $key=>$value){ // iterate through array
      echo $key.'has scored total score:-'.$value; //print the score along with username
}
?>

注意:-请以不会产生任何歧义的方式使用变量名。

关于php - 从未存储在mysql中的PHP获取TOTAL值的排名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38114102/

10-12 15:06