dg9495
dg9495

Reputation: 13

How to check equality of two arrays when the key_names are different in laravel

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.

Upvotes: 0

Views: 80

Answers (2)

Viduranga
Viduranga

Reputation: 520

By using Laravel Collection :

$array1 = [["id"=>15],["id"=>16],];

$array2 = [["answer_option_id"=>16],["answer_option_id"=>15]];

$array_1 = collect($array1)->pluck('id')->sort()->values()->all();
$array_2 = collect($array2)->pluck('answer_option_id')->sort()->values()->all();

if($array_1 == $array_2){
       echo "correct";
}else{
       echo "incorrect";
}

Upvotes: 1

Foued MOUSSI
Foued MOUSSI

Reputation: 4813

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 Illuminate\Support\Arr::flatten() helper
// $answerOptionsIds = Illuminate\Support\Arr::flatten($array2);

$array1 = [["id" => 15], ["id" => 16]];

$correctAnswersIds = [];
foreach($array1 as $value) {
    $correctAnswersIds[] = $value['id'];
}
// $correctAnswersIds => [15, 16]
// OR 
// $correctAnswersIds = Illuminate\Support\Arr::flatten($array1);

$match = true;

foreach($correctAnswersIds as $correctAnswer) {

   if (!in_array($correctAnswer, $answerOptionsIds)) { 
      $match = false;
      break;
   } 
}

Upvotes: 0

Related Questions