我正在测试一个有十个问题的测验。除了第二个(填空)和最后一个,所有都是多项选择,这需要用户从六个复选框中选择三个。
这是答案键和评分脚本:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$correct = 0;
$answers = array(1 => array('A'),
2 => array('Mars'),
3 => array('C'),
4 => array('D'),
5 => array('A'),
6 => array('C'),
7 => 'C',
8 => 'C',
9 => 'B',
10 => array('A','B','C'));
$total = count($answers);
foreach($answers as $num => $answer){
$qa = $_POST['q'.$num.''];
if(is_array($answer)){
if(array_diff($qa, $answer) == array()){
$correct++;
}
} else if($qa === $answer){
$correct++;
}
$grade= ($correct/count($answers))*100;
}
}
echo '<div style="background: #ff0;">Score '.$grade.'%</div>';
echo '<br>var_dump: ';
var_dump($_POST);
如果我将所有十个问题都正确,它会显示正确的数组(下方),但我得到的分数为70%而不是100%。如果我把前两个问题弄错了但所有其他问题都是正确的,我会得到50%,而不是80%。
任何人都可以看到我的评分脚本有问题,或者您认为问题出在我的测验代码的其他地方?
var_dump: array(12) { ["q1"]=> array(1) { [0]=> string(1) "A" } ["q2"]=> array(1) { [0]=> string(7) "Mars" } ["q3"]=> array(1) { [0]=> string(1) "C" } ["q4"]=> array(1) { [0]=> string(1) "D" } ["q5"]=> array(1) { [0]=> string(1) "A" } ["q6"]=> array(1) { [0]=> string(1) "C" } ["q7"]=> array(1) { [0]=> string(1) "C" } ["q8"]=> array(1) { [0]=> string(1) "C" } ["q9"]=> array(1) { [0]=> string(1) "B" } ["q10"]=> array(3) { [0]=> string(1) "A" [1]=> string(1) "B" [2]=> string(1) "C" } ["PreviousURL"]=> string(25) "http://g1/test/gw-intro" ["user_token"]=> string(13) "54f3d1ac48555" }
答案 0 :(得分:1)
希望这能回答你的问题 - 它在我做过的随机试验中起作用。如果它不能正常工作,请告诉我,并请提供更多详细信息。
<?php
$correct = $answered = 0; //Correct Total.
$answers = array(1 => array('A'),
2 => array('Mars'),
3 => array('C'),
4 => array('D'),
5 => array('A'),
6 => array('C'),
7 => 'C',
8 => 'C',
9 => 'B',
10 => array('A','B','C'));
$_POST = [
'q1'=>['A'],
'q2'=>['Mars'],
'q3'=>['C'],
'q4'=>['D'],
'q5'=>['A'],
'q6'=>['C'],
'q7'=>'C',
'q8'=>'C'
]; //I did this to run the algorithm without needing to make up a form.
foreach($answers as $key => $values){
if(!key_exists('q'.$key, $_POST)) //Key does not exist in the POST data sent by the browser, answer is therefore wrong.
$answered++; //Increase the "answered" count, but do not increase the correct count
else{
$answer = $_POST['q'.$key];
if($answer === $values){
//If the answer is exactly equal to the value in the answer array, it is correct.
//I'm assuming you format the answers as you need.
$correct++;
$answered++;
}else{
$answered++;
}
}
}
echo "Your Score is: {$correct}/{$answered}, or ". (($correct/$answered)*100)."%";
&GT;
答案 1 :(得分:0)
抱歉,这是一个蹩脚的问题。我确认评分脚本正在运行。唯一的问题是,如果你不回答某个特定问题,那就不算错。因此,如果你只回答一个问题并且你做对了,那就是1分之一,或100%,当它应该是10%。