我正在准备一个小测验,它可以对一个问题有很多答案。复选框使用数组存储,并通过ab_name列对我的ab_name表进行检查(其中存储正确的答案)。
我所要做的就是--如果选中的答案在answers_bank表中,它会回显它的“正确”,否则它会对不正确的复选框回显“不正确”。
我尝试过的方法不起作用,因为它在每次迭代期间比较数组中的每个单独的答案,并返回不正确的其他答案(因为它是不相等的)。这张照片应该能解释我的问题:

下面是我设置的代码片段:
返回复选框问题,如图像的第一部分所示:
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>";
}
}
}
}}
对此我还能做什么其他的解决方案或修正吗?非常感谢!
发布于 2016-03-22 17:48:11
首先存储所有正确的答案,这样您就不必同时遍历它们和表单的响应。相反,您只需循环表单响应,并检查所选值是否位于正确响应数组中。
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>";
}
}
}https://stackoverflow.com/questions/36153315
复制相似问题