我正在设置一个测验,可以为一个问题提供很多答案。复选框使用数组存储,并使用answers_bank
列(存储正确答案的位置)对ab_name
表进行检查。
我想要做的就是 - 如果检查的答案都在answers_bank表格中,那么它就会回复""#14;正确"否则就会回复" s" s"错误" 34;对于不正确的复选框。
我尝试这样做的方式不起作用,因为它在每次迭代期间比较数组中的每个单独答案,并且对于其他答案返回不正确(因为它不相等)。这张图片应该解释我遇到的问题:
以下是我设置的代码片段:
返回复选框问题,如图片的第一部分所示:
foreach ($qresults as $aresults) {
$selected = $aresults["ab_name"];
$ab_id = $aresults["ab_id"];
?>
<input type="checkbox" name="checkbox[]"
value="<?php echo $aresults["ab_name"]; ?>"> <?php echo $aresults["ab_name"]; ?> <br>
<?php
}
?>
旨在检查答案是否正确
foreach ($results as $row) {
$qb_id = $row['qb_id'];
$q_answer = $_POST["q$qb_id"];
$sql = "SELECT * FROM answers_bank WHERE ab_qb_id = :qb_id AND ab_correct = :correct";
$stmt = $db->prepare($sql);
$stmt->bindValue(':qb_id', $qb_id);
$stmt->bindValue(':correct', "correct");
$stmt->execute();
$qresults = $stmt->fetchAll();
foreach ($qresults as $cresults) {
if (is_array($q_answer)) {
foreach ($q_answer as $checkbox) {
if ($checkbox == $cresults["ab_name"]) {
echo "You said : " . $checkbox . " ... which is the correct answer!</br>";
} else if ($checkbox != $cresults["ab_name"]) {
echo "You said : " . $checkbox . " ... which is incorrect</br>";
}
}
}
}
}
我可以对此做出任何其他解决方案或更正吗?非常感谢!
答案 0 :(得分:2)
首先存储所有正确的答案,这样您就不必遍历它们和表单中的响应。相反,您可以循环遍历表单响应并检查所选值是否在正确响应的数组中。
foreach ($results as $row) {
$qb_id = $row['qb_id'];
$q_answer = $_POST["q$qb_id"];
$sql = "SELECT * FROM answers_bank WHERE ab_qb_id = :qb_id AND ab_correct = :correct";
$stmt = $db->prepare($sql);
$stmt->bindValue(':qb_id', $qb_id);
$stmt->bindValue(':correct', "correct");
$stmt->execute();
$qresults = $stmt->fetchAll();
$correct_answers = array();
foreach ($qresults as $cresults) {
array_push($correct_answers, $cresults["ab_name"]);
}
if (is_array($q_answer)) {
foreach ($q_answer as $checkbox) {
if (in_array($checkbox, $correct_answers)) {
echo "You said : " . $checkbox . " ... which is the correct answer!</br>";
} else {
echo "You said : " . $checkbox . " ... which is incorrect</br>";
}
}
}