Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 当laravel中的键名称不同时,如何检查两个数组的相等性_Php_Laravel - Fatal编程技术网

Php 当laravel中的键名称不同时,如何检查两个数组的相等性

Php 当laravel中的键名称不同时,如何检查两个数组的相等性,php,laravel,Php,Laravel,我是laravel的初学者,但请帮我解决这个问题。最近我正在创建一个问答应用程序。应用程序也有一些多选mcq问题。为了匹配那些多选mcq答案和正确答案,我需要匹配两个数组并得到结果 例:- 注意:数组1包含正确的选项(正确答案)。array2包括用户提供的选项。array2可以有任意长度。因为在多选题中,我们可以选择任意数量的答案选项 但是,要知道用户是否给出了正确的选项,我需要将array2与array1匹配,并且它们必须相等。 我尝试了一些内置函数,如array\u intersect(),

我是laravel的初学者,但请帮我解决这个问题。最近我正在创建一个问答应用程序。应用程序也有一些多选mcq问题。为了匹配那些多选mcq答案和正确答案,我需要匹配两个数组并得到结果

例:-

注意:数组1包含正确的选项(正确答案)。array2包括用户提供的选项。array2可以有任意长度。因为在多选题中,我们可以选择任意数量的答案选项

但是,要知道用户是否给出了正确的选项,我需要将array2与array1匹配,并且它们必须相等。
我尝试了一些内置函数,如array\u intersect(),但没有成功。

您必须拥有有效的PHP数组

$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;
   } 
}

使用Laravel系列:

$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";
}

它是一个laravel集合吗?使用集合代替数组。
$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";
}