在我的一个php应用程序中,有一个竞赛部分。它包含10个问题的多项选择,每个问题有4个选项。
用户填写表单后,我将答案保存为db中的逗号分隔值。如下:
user | answer
-------------------------------------
112 | 1,7,8,9,8,5,2,3,6,7,9,6
我得到了一个与使用的填充答案密钥相同的答案密钥..
评估用户输入并找出得分最高的用户的最佳逻辑方法是什么?
答案 0 :(得分:1)
正如评论中所提到的,这不是存储数据的最佳方式,但我会这样评估:
$query = mysql_query("select * from `table` where 1",CONNECTION_IDENTIFIER) or die("die message");
$answer_key = array(answer1,answer2,etc);
$high_score = 0;
$high_scorer= "";
while($r=mysql_fetch_array($query)){
$users_answers = explode(',',$r['answer']);
$user_score = 0;
for($i=0;$i<10;$i++){
if ($answer_key[$i]==$users_answers[$i]){
$user_score++;
}
}
if ($user_score > $high_score){
$high_score = $user_score;
$high_scorer = $r['user'];
}
}
echo "High scorer is $high_scorer with $high_score points";
答案 1 :(得分:1)
如果你有这样的分数答案:
$ answersRating = array(1 =&gt; 0 =&gt; 1,3 =&gt; 3,4 =&gt; 2,......),当选择答案1时,他得到0分,2 =&gt; ;一点,对于3 =&gt; 3分等等。你可以这样做:
$score = array_sum(array_intersect_key($answersRating, array_flip(explode(',', $userAnswersStringFromDB))));
答案 2 :(得分:1)
我认为你应该像这样构建你的数据库: 注意:这是最低限度的,您当然会在名称,描述等问题上添加额外的字段
answers | id, user_id, question_id, answer
questions | id, contest_id, correct_answer
user | id, name
然后你可以通过查询获得所有内容。
最高分:
SELECT u.name,count(*) as Score FROM user u, answers a, questions q WHERE u.id=a.user_id and q.id = a.question_id and q.correct_answer=a.answer WHERE q.contest_id=XXX ORDER BY Score