您还可以使用更复杂的数组来设置问题表单,然后检查答案。考虑一下你是否有这个数组:
$questions = array(
array(
"question" => "What color is the sky",
"answers" => array(
"red",
"green",
"blue",
"penquine"
),
"correct_answer" => 2
),
array(
"question" => "What is the bestest langugage in the world!",
"answers" => array(
"C#",
"English",
"Brainfuck",
"PHP",
),
"correct_answer" => 3
),
);
在提出问题的页面中,您可以通过遍历数组并打印每个问题及其答案来创建表单。有点像:
echo "<form action='check_answers.php' method='post'>\n";
foreach ($questions as $qi => $q) {
echo "<h1>{$q["question"]}</h1>\n";
foreach ($q["answers"] as $ai => $answer) {
echo "<label><input type='radio' name='answers[$qi]' value='$ai'> $answer</label>\n";
}
}
echo "<input type='submit'></form>";
然后可以check_answers.php
通过将每个问题中的“correct_answers”元素与表单提供的值进行比较,在文件中检查数据。
if (isset($_POST["answers"]) && is_array($_POST["answers"])) {
$correctAnswers = array();
$incorrectAnswers = array();
foreach ($_POST["answers"] as $question => $answer) {
if ($questions[$question]["correct_answer"] == $answer) {
$correctAnswers[] = $questions;
}
else {
$incorrectAnswers[] = $question;
}
}
echo "You had " . count($correctAnswers) . " correct answers.<br>\n";
echo "You had " . count($incorrectAnswers) . " incorrect answers.<br>\n";
}
您甚至可以扩展它以准确显示用户错误的问题和正确的问题,因为两者的索引都存储在数组中。
该$questions
数组虽然在上面的示例中是静态的,但也可以很容易地从 MySQL 模式生成。
function generateQuestions(\PDO $pdo) {
$questions = array();
$sql = "SELECT id, question FROM questions";
$result = $pdo->query($sql);
foreach ($result as $row) {
$question = array(
"question" => $row["question"],
"answers" => array(),
"correct_answer" => 0
);
$answerSql = "SELECT id, answer, isCorrect FROM answers
WHERE question_id = {$row["id"]}";
$answerResult = $pdo->query($answerSql);
foreach ($answerResult as $answer) {
$answers[$answer["id"]] = $answer["answer"];
if ($anser["isCorrect"]) {
$question["correct_answer"] = $answer["id"];
}
}
$questions[$row["id"]] = $question;
}
return $question;
}