【发布时间】:2022-01-09 18:29:32
【问题描述】:
我试图创建一个函数,在用户回答测验后计算正确答案。该函数在用户回答完所有问题并单击“提交”按钮后运行。
测验在数据库中有 10 个问题,但用户每次考试只能随机选择 5 个问题。 即使我正确回答了所有 5 个问题,该函数仍会返回只有 1 个正确答案。我还对所有变量、请求和获取执行了 dd(),它们显示了所需的值,所以我假设循环运行一次然后中断,但可能是什么原因造成的?
在 ExamController 中:
public function calculateResults(){
// variable that is incremented per correct answer
$totalCorrect = 0;
// array of ids of the questions the user has taken (out of 10 questions in DB, only 5
questions in random order are taken by the user
$takenQuestions = request()->input('taken_questions');
//array of answers provided by user (multiple choice)
$givenAnswers = request()->input('answer');
// get exam id
$exam_id = request()->input('exam_id');
// get all exam questions from DB
$examQuestions = examQuestion::where('exam_id',$exam_id);
// loop through each question that was available in the exam
for($i = 1; $i<=count($takenQuestions);$i++){
// get the question from the exam DB that matches the questions taken by the user
$givenQuestion = $examQuestions->find($takenQuestions[$i]);
//if questions match
if(isset($givenQuestion)){
// get the question's correct answer
$correctAnswer = $givenQuestion->answers->firstWhere('isCorrect',true);
//check if the correct answer and user's given answer matches
if($correctAnswer->content == $givenAnswers[$i]){
//if they match increment correct answer variable
$totalCorrect++;
}
}
}
dd($totalCorrect);
}
我已经检查并执行了dd() 和echo 以下内容:
-
count($takenQuestions)在 for 循环的第二个条件中根据需要返回 5(所以这不是原因) -
$i在第一个循环中返回 1(根据需要),然后 echo 命令不再重复。 - 编辑:
$takenQuestions返回用户在考试中回答的 5 个问题的question IDs的数组(它们是随机选择的) 例如当我dd($takenQuestions)
Taken Questions:
array:5 [▼
1 => "1"
2 => "2"
3 => "3"
4 => "5"
5 => "10"
]
问题 ID 为 1、2、3、5、10 的意义问题是用户回答的问题
【问题讨论】:
-
$takenQuestions的值是多少?你能dd($takenQuestions) -
$takenQuestions返回用户在考试中回答的 5 个问题中的question IDs的数组(它们是随机选择的)` Taken Questions: array:5 [▼ 1 => "1 " 2 => "2" 3 => "3" 4 => "5" 5 => "10" ] ` 问题 ID 为 1,2,3,5,10 的问题是用户回答的问题