【问题标题】:For loop breaks after first loop (Laravel Controller)对于第一个循环后的循环中断(Laravel 控制器)
【发布时间】: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 的问题是用户回答的问题

标签: php for-loop laravel-8


【解决方案1】:

$givenAnswers 变量的内容是什么?

它是按与问题相同的顺序(即 1、2、3、4、5)编入索引,还是按问题 ID(1、2、3、5、10)编入索引?您当前的代码假定第一个,但后者似乎更有可能。

如果它是按问题 ID 而不是数组索引来索引的,您的代码应该是:

if($correctAnswer->content == $givenAnswers[$takenQuestions[$i]]){
    //if they match increment correct answer variable
    $totalCorrect++;
}

【讨论】:

    猜你喜欢
    • 2015-01-13
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2021-05-26
    • 2021-09-15
    • 1970-01-01
    相关资源
    最近更新 更多