2017-07-31 110 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; 
}