PHP多个答案测验 - 检查正确的答案组合

时间:2017-05-10 13:26:42

标签: php

尝试使用PHP编程的第一步,一个允许多个答案的测验,但某个组合,如答案选项2& 3应该给你一个分数。包含这些值是不够的,因此只需选择所有答案就不会得分。

到目前为止一切都有效,但检查正确答案和增加分数的条件不起作用,我不知道为什么。我没有人问,所以我依靠你。请问谁能开导我?

我的HTML:

<form action="result.php" method="post" id="quiz">
 <div>
  <input type="checkbox" name="question-1-answers[]" id="question-1-answers-A" value="A" />
  <label for="question-1-answers-A">ABCD </label>
 </div>

 <div>
  <input type="checkbox" name="question-1-answers[]" id="question-1-answers-B" value="B" />
  <label for="question-1-answers-B">EFGH</label>
 </div>

 <div>
  <input type="checkbox" name="question-1-answers[]" id="question-1-answers-C" value="C" />
  <label for="question-1-answers-C">KLMN</label>
 </div>

 <div>
   <input type="checkbox" name="question-1-answers[]" id="question-1-answers-D" value="D" />
   <label for="question-1-answers-D">OPQR</label>
 </div>

        <input type="submit" value="Submit Quiz" />
</form>

我的结果.php:

<?php
  $totalscore = 0;

  if(!empty($_POST['question-1-answers'])) {               
  echo "You selected the following answer(s): <br/>";
foreach($_POST['question-1-answers'] as $selected) {
echo $selected;

     // now checking if answer was the right combination
 if ($selected == "BC") {
     echo ('condition met!');
 $totalscore++;
 }
    }

   echo "<div id='results'>$totalscore out of 1</div>";
   }
 ?>

即使我选择B&amp; C,条件永远不会发生。所选$的内容虽然显示正确答案。 (&#34; BC&#34;)在这种情况下。

为什么不解雇?我在这里俯瞰什么?

2 个答案:

答案 0 :(得分:0)

$ _ POST ['question-1-answers']是一个数组,所以你需要检查B和C是否在

尝试类似

的内容
if(in_array($_POST['question-1-answers'], 'A') && in_array($_POST['question-1-answers'], 'B'))
   $totalScore++;

或者如果你不想要很多条件

$selected = '';
foreach ($_POST['question-1-answers'] as $key => $value) {
    $selected .= $value;
}
if($selected == 'BC')
    $totalScore++;

答案 1 :(得分:-1)

foreach($_POST['question-1-answers'] as $selected) {
echo $selected; // your var will be B, then C if both were selected by player

// now checking if answer was the right combination
if ($selected == "BC") { 
// here, you try checking if 'B equals BC' or if 'C equals BC'
// no matter what player answered, it'll never match
// YOU ARE IN A LOOP -> one round / one answer
 echo ('condition met!'); // will never be true
$totalscore++;
}
}
  

你需要在循环中连接变量$selected,然后在循环外部,与正确答案组合进行比较

相关问题