그런 다음 답을 확인하십시오. 이 배열이 있다면 고려 : 질문을 묻는 페이지에서
$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>";
데이터는 다음 형태로 제공된 값과 각 질문에 "correct_answers"요소를 비교함으로써 check_answers.php
파일을 확인할 수 있었다.
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;
}
왜 게시물 배열 –