逐个比较数组

时间:2017-07-31 11:52:46

标签: php arrays

当我print_r时,我有这个数组输出 来自数据库的数组

$answer --> Array ( [id] => 251 [question_id] => 242 [text] => something 
 [order] => 4 [deleted] => 0 )

以及用户选择的数组

//Array ( [0] => 254 [1] => 251 [2] => 252 [3] => 253 )

我需要以某种方式比较来自db [id]=>251 to compare with [0] => 254的每个答案我可以使用什么,array_diff或者cross或其他函数,谢谢

6 个答案:

答案 0 :(得分:1)

简单使用in_array函数在数组中搜索specific value

in_array($answer['id'],$selects);

答案 1 :(得分:0)

您可以使用array_filter过滤db:

中的答案
$myAnswers = array_filter($answers, function($answer) use ($selectedAnswers) {
    return in_array($answer['id'], $selectedAnswers);
});

var_dump($myAnswers);

答案 2 :(得分:0)

试试这个简单的

$answer = array('id'=>'251','question_id'=>'242','order'=>'4','deleted'=>0);
$answerArray  = array('254','251','252','253');

foreach ($answerArray as $key => $value) {
        if($answer['id'] == $value){
            echo "Right answer is". $value;
        }
}

希望它有所帮助!

答案 3 :(得分:0)

您可以使用array_search

喜欢那个

$answer = Array ( 
    "id" => 251,
    "question_id" => 242,
    "text" => "something",
    "order" => 4,
    "deleted" => 0 
);

$ids= array(254,251,252,253);

$key = array_search($answer["id"], $ids);

if($key){
    echo "Find - Key: " . $key . " and ID: " $ids[$key];
}

答案 4 :(得分:0)

如果你的$ answer数组是多维数组,你可以找到这样的prent id

$data= [['id' => 251 ,'question_id' => 242 ,'text' => 'something','order' => 4 ,'deleted' => 0 ]];
$selectors=[254,251,252,253];
$presentIds=[];
foreach ($selectors as $selector){
    if(in_array($selector,array_column($data,'id'))){
        $presentIds[]=$selector;
    }
}

此处$presentIds包含所有现有ID。

答案 5 :(得分:0)

我为check question id创建了一个函数。希望它会有用

Dairy