I am a beginner to laravel yet please help me to figure this out.I’m creating a question/answer app these days. The application have some multi choice mcq questions aswell. Inorder to match those multi choice mcq answers with correct answers, I need to match two arrays and get results.
Ex:-
array1 = [{"id":15},{"id":16}] array2 = [{"answer_option_id":15},{"answer_option_id":17}]
Note : array1 includes the correct options (correct answer). array2 includes the options given by user.array2 can have any length.Because in multi choice question, we can select any number of answer options.
But, to know if the user have given the correct options, I need to match array2 with array1 and they must be equal. I tried some built_in functions such as array_intersect() but it didn’t work.
Advertisement
Answer
You must have Valid PHP Arrays
$array2 = [["answer_option_id" => 15], ["answer_option_id" => 17]]; $answerOptionsIds = []; foreach($array2 as $value) { $answerOptionsIds[] = $value['answer_option_id']; } // $answerOptionsIds => [15, 17] // OR you can make use of IlluminateSupportArr::flatten() helper // $answerOptionsIds = IlluminateSupportArr::flatten($array2); $array1 = [["id" => 15], ["id" => 16]]; $correctAnswersIds = []; foreach($array1 as $value) { $correctAnswersIds[] = $value['id']; } // $correctAnswersIds => [15, 16] // OR // $correctAnswersIds = IlluminateSupportArr::flatten($array1); $match = true; foreach($correctAnswersIds as $correctAnswer) { if (!in_array($correctAnswer, $answerOptionsIds)) { $match = false; break; } }