【发布时间】:2018-05-16 18:31:03
【问题描述】:
我正试图在这里弄清楚一些事情。
我有一个未序列化的数组,其中包含从数据库中出来的多项选择题。
我需要这个循环,所以当这个人提交答案时,评分页面需要知道需要多少次循环才能获得正确和错误的答案。
我的问题是它通过一个测试问题额外计算一次,并在最后给出错误的结果。例如,当只有一个问题时说“你答对了 2 个问题”。
这是从数据库中打印出来的数组,考生在提交答案之前会看到它。
<form class="create-test" action="grade.php" method="POST">
<?php
$numberOfLoops = 1;
foreach ($testArray as $testArray['row']) {
//echo $testArray['row']['choice1'];
//}
//for ($i = 1; $i <= $quantity; $i++){
?>
<label for='test-question'><?php echo $testArray['row']['question']; ?></label>
<!-- Loop to go through the question array from the database, to be posted to the grading funciton -->
<select class = 'form-control' name="Question<?php echo $numberOfLoops; ?>">
<option value="Select an answer" disable selected hidden>Select an answer</option>
<option value="<?php echo $testArray['row']['choice1']; ?>"><?php echo $testArray['row']['choice1']; ?></option>
<option value="<?php echo $testArray['row']['choice2']; ?>"><?php echo $testArray['row']['choice2']; ?></option>
<option value="<?php echo $testArray['row']['choice3']; ?>"><?php echo $testArray['row']['choice3']; ?></option>
</select>
<input type="hidden" class='form-control' id='actanswer' name="actanswer<?php echo $numberOfLoops; ?>" value="<?php echo $testArray['row']['answer']; ?>">
<div class="line"></div>
<?php
$numberOfLoops++;
}
echo "<input type='hidden' name='numberOfLoops' value='".$numberOfLoops."'>";
?>
<input type='hidden' name='test-id' value="<?echo $testID; ?>">
<button type="submit" class="btn btn-primary btn-lg" name='submit-answers'>Submit Answers</button>
</form>
这是寻找答案的 for 循环。
$correct = 0;
$incorrect = 0;
$num = $_POST['numberOfLoops'];
echo $num;
for ($x = 1; $x <= $num; $x++) {
$response = $_POST['Question'.$x];
echo $response."<br>";
$answer = $_POST['actanswer'.$x];
echo $answer."<br>";
if($answer == $response){
$correct++;
}elseif($response !== $answer){
$incorrect++;
}
}
不管有多少问题,它总是会多算一个。
感谢所有帮助和反馈。
编辑:作为进一步的信息,有一个回显标签会说你得到了 x 正确和 y 不正确。如果测试是两个问题,它会说。 “你答对了 3 题,答错了 0 题。”尽管只有两个问题。
【问题讨论】:
-
告诉我们
test array -
这看起来很危险
foreach ($testArray as $testArray['row'])为什么不做一个简单的foreach ($testArray as $row)并避免弄乱你的输入数组 -
$testArray 被声明为未序列化的测试,它被保存到包含多个测试的表中。你是说,在它被反序列化之后,声明 $row = ['row']?