2017-07-31 85 views
0

我有数组这个输出,当我的print_r 从数据库比较数组逐个

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

和阵列自带

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

我需要的用户selectes莫名其妙地比较各数组答案来自分贝[id]=>251 to compare with [0] => 254我可以使用什么,array_diff或相交或其他功能,谢谢

+2

根据您的要求使用循环 –

+0

您可以使用'array_values($ answer)'它返回具有整数索引的数组。因此您可以使用循环轻松进行比较。 – Niroshan

+0

简单使用in_array'in_array($ answer ['id'],$ choose);' – JYoThI

回答

0

您可以使用array_filter从数据库过滤答案:

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

var_dump($myAnswers); 
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; 
     } 
} 

希望它能帮助!如果你的$答案数组是多维数组,你可以

+0

谢谢,但我在foreach循环$回答这样的:foreach($ question_answers as $ answer){ foreach($ user_answer as $ key => $ value){ $ value; if($ value == $ answer ['id']){ echo“ok ===>”。$ value。 “
”; } else { echo“no -------------------------------->”。$ value。 “
”; } }它显示了很多答案 – ylli

+0

为什么你使用两个foreach循环查看我的答案 – kunal

1

简单的使用in_array功能搜索一个specificvalue

in_array($answer['id'],$selects); 
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]; 
} 
0

找到像这样的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。

0

我创建了一个检查问题ID的函数。希望它有用

function checkAnswer($question1, $question2) { 

    $indexed_array1 = array_values($question1); 
    $indexed_array2 = array_values($question2); 

    if ($indexed_array1[0]==$indexed_array2[0]) { // for check the answer && $indexed_array1[n]==$indexed_array2[n] | if the answer index is 'n' 
     return true; 
    } 
    return false; 
}