0

我有一个像这样的多项选择测验问题的 php 页面

<p>1. Is Manhattan near New York?<br>
    <input type="radio" name="ans1" value="3">
    Yes<br>
    <input type="radio" name="ans1" value="2">
    Maybe<br>
    <input type="radio" name="ans1" value="1">
    No</p>
  <p>2. Do you like Indian food?<br>
    <input type="radio" name="ans2" value="1">
    Some times<br>
    <input type="radio" name="ans2" value="3">
    Never<br>
    <input type="radio" name="ans2" value="2">
    Always</p>

该页面向自身发布并检查答案是否正确

if($ans1 == "3") { 
$test_complete .="Question one is <span class='green'>correct</span>, well done!<br/>";  
}else{ 
$test_complete .="Question one is <span class='red'>incorrect</span>!<br/>"; 
} 
// change the quest2 to the right answer
if($ans2 == "2") { 
$test_complete .="Question two is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question two is <span class='red'>incorrect</span>!<br/>"; 
}

现在,我不想告诉用户答案一或两个是正确的,而是运行一个计数器,它计算正确答案的数量和错误答案的数量,并将其显示在两个表格框中,一个框显示问题总数。

4

3 回答 3

1

像这样...?

$result = $ans1 == 3;
$result += $ans2 == 2;
$result += $ans3 == 1;

echo "You got $result/3 questions right";

http://codepad.org/6zBQXQIT

于 2012-05-07T10:48:27.003 回答
1

有多种方法可以做到这一点。我会有一系列与问题相对应的正确问题,然后进行比较。例如:

$correct_answers = array('3', '2');
for ($i = 0; $i < $number_of_questions; $i++)
{
   $ans_var = 'ans'.$i;
   if ($_POST[$ans_var] == $correct_answers[$i])
   {
      $score++;
   }
}
于 2012-05-07T10:49:50.673 回答
0

如果我正确理解了这个问题...

session_start();
if (!isset($_SESSION['total'])){$_SESSION['total']=0;}
if (!isset($_SESSION['correct'])){$_SESSION['correct']=0;}
if($ans1 == "3") {$_SESSION['correct']+=1;}
if($ans2 == "2") {$_SESSION['correct']+=1;}
if (isset($ans1) || isset($ans2)) {$_SESSION['total']+=1}
echo '<table><tr><td>Correct answers:</td><td>'.$_SESSION['correct'].'</td></tr>';
echo '<tr><td>Wrong answers:</td><td>'.$_SESSION['total']-$_SESSION['correct'].'</td></tr>';
echo '<tr><td>Total answers</td><td>'.$_SESSION['total'].'</td></tr></table>';
于 2012-05-07T10:53:43.733 回答