I'm trying to set up a simple quiz module. I'm using a Matrix field called quiz, with a plain text question field and an answers table field. In the table field, there's two columns, plain text answer and checkbox correct. See image:
The idea being that there's only one correct answer.
EDIT: Using James' amazing code as a base, I've tried to get that into PHP and it's coming along ok. Still working on it...
$userAnswers = Craft::$app->getRequest()->getBodyParam('answers');
$user = Craft::$app->getUser()->getIdentity();
$allQuestions = $quiz->quizMatrix->all();
$numberOfQuestions = count($allQuestions);
$correctAnswersByQuestion = [];
foreach ($allQuestions as $question) {
$correctAnswer = array_map(function($answer) {
return (bool)$answer['correct'];
}, $question['answers']);
$correctAnswersByQuestion[] = $correctAnswer;
}
$totalCorrect = 0;
foreach ($userAnswers as $key => $value) {
$questionIndex = $key;
$answerIndex = $value;
$isCorrect = $correctAnswersByQuestion[$questionIndex][$answerIndex];
echo "<p>Question " . ($questionIndex+1) . " was " . ($isCorrect ? 'correct' : 'incorrect') . "</p>";
$totalCorrect += $isCorrect ? 1 : 0;
}
$score = ($totalCorrect / $numberOfQuestions) * 100;
$data = 'Your score is '.$score.'%';
$response = Craft::$app->getResponse();
$response->data = $data;
return $response;
