我为我的学生做了一个简单的基于PHP的考试。 结果记录为" q1"," q2"," q3"," q4"和" q5"在数据库中。
正确答案记录为"是"并且错误答案为" no"。
有5个问题,我希望总分为100。
所有功能都可以像我一样工作,但问题是,我不知道如何将结果从高到低排序。任何帮助都非常感谢!
$result = mysqli_query($db,"SELECT * FROM table");
while($row = mysqli_fetch_array($result)){
$score = 0;
echo '<img alt="'.$row["name"].'" src="images/'.$row["name"].'.jpg" width="118" height="158"';
if ($row["q1"] === "yes") {$score=$score+20;}
if ($row["q2"] === "yes") {$score=$score+20;}
if ($row["q3"] === "yes") {$score=$score+20;}
if ($row["q4"] === "yes") {$score=$score+20;}
if ($row["q5"] === "yes") {$score=$score+20;}
echo ' /> '.$row["name"] . ' ' . $score;
}
答案 0 :(得分:6)
您可以使用while
和if
结果列执行所有操作,而不是select
和内部order by
,例如:
select name, if(q1='yes', 20, 0) +
if(q2='yes', 20, 0) +
if(q3='yes', 20, 0) +
if(q4='yes', 20, 0) +
if(q5='yes', 20, 0) result
from table
order by result desc
答案 1 :(得分:0)
$result = mysqli_query($db,"SELECT * FROM table");
//I sugges you to first store the information into an array:
$scores = [];
while($row = mysqli_fetch_array($result)){
$score = 0;
//Calculate the score
if ($row["q1"] === "yes") {$score=$score+20;}
if ($row["q2"] === "yes") {$score=$score+20;}
if ($row["q3"] === "yes") {$score=$score+20;}
if ($row["q4"] === "yes") {$score=$score+20;}
if ($row["q5"] === "yes") {$score=$score+20;}
//Push it into the array
array_push($scores, array("name" => $row["name"],
"image" => 'src="images/'.$row["name"].'.jpg"',
"score" => $score
));
}
对数组进行排序:(Sort Multi-dimensional Array by Value)
usort($scores, function($a, $b) {
return $b['score'] - $a['score'];
});
//Do as you wish with the array
print_r($scores);