Php 使用in_数组函数比较两个数组

Php 使用in_数组函数比较两个数组,php,laravel,Php,Laravel,我有两个数组需要在_数组中进行比较,但由于某些原因它无法比较,只有当我像这样在_数组(294,$answer)中手动替换时,它才会显示为true $answers ----> // Array ( [0] => 294 [1] => 296 ) $answer ---> // Array ( [id] => 294 [question_id] => 87 [correct] => 1 ) in_array($answers, $answer) in

我有两个数组需要在_数组中进行比较,但由于某些原因它无法比较,只有当我像这样在_数组(294,$answer)中手动替换时,它才会显示为true

$answers ----> // Array ( [0] => 294 [1] => 296 )
$answer  --->  // Array ( [id] => 294 [question_id] => 87 [correct] => 1 )
in_array($answers, $answer)

in_array
用于搜索数组中的字符串,因此您应该尝试从answers数组传递单个值,而不是整个数组

例如—

$answers = array(294, 296);
$answer = array('id' => 294, 'question_id' => 87, 'correct' => 1 );

foreach ( $answers as $answer_id ) {

    $check = in_array($answer_id, $answer);

    echo "<pre>";
    var_dump( $check );
    echo "</pre>";
}
$answers=array(294296);
$answer=array('id'=>294,'question_id'=>87,'correct'=>1);
foreach($answers as$answer\u id){
$check=in_数组($answer_id,$answer);
回声“;
var_dump($支票);
回声“;
}

您似乎有一个答案(
$answer=array(294,'question_id'=>87,'correct'=>1);
)由
id
(value
294
)标识,您需要找出这个答案是否是有效答案之一,其
id
存储在列表中(
$answers=array(294296)

PHP函数是要使用的工具,只需正确使用它。将
$answers
的ID搜索到
$answers
中存储的ID列表中:


阅读更多关于数组的内容,在到达该部分之前不要离开阅读内容。

在_array()中。
用于比较一个字符串值与数组,而不是两个数组。在数组中使用
($answers[0],$answer)
array\u interact()
你可以试试
$answer['id']
你读过的文档了吗?另请阅读手册中的@RJParikh用法:
bool in_数组(mixed$needle,array$haystack[,bool$strict=FALSE])
意思是在数组中可以将字符串和数组作为指针处理。在in_数组()函数中,第一个参数必须是字符串,而不是数组。为什么
in_数组($answer\u id,$answer)
?唯一可以(而且应该)找到
$answer\u id
值的地方是
$answer['id']
。他想在
$answer
内检查
$answers
。你做了相反的事情。@AlivetoDie这种需要有什么意义?因为可能他的两个数组都有更多的元素/子数组,那么你的代码将只停留在第一次迭代中。目前OP’在两个数组中只显示单个记录,但是我们必须考虑每一个方面。
$answer = array('id' => 294, 'question_id' => 87, 'correct' => 1 );
$answers = array(294, 296);

if (in_array($answer['id'], $answers)) {
    echo("Good answer");
} else {
    echo("Answer not found in list");
}