你也可以使用更复杂的阵列都建立问题表格然后检查答案。试想,如果你有这个数组:
$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";
}
你甚至可以扩展,为precicely哪些问题的用户得到了错误的和正确的,因为两个指标都存储在阵列中显示。
$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;
}
为什么不做一个foreach()循环通过post数组 – 2013-07-11 00:20:40