2017-08-01 77 views
1

我有這段代碼,我想比較從數據庫來的數據與一個用戶選擇,但它似乎foreach($question_answers as $answer){foreach ($user_answer as $key => $value) {它不好,它是重複4倍多,我需要一種比較$user_answer的方式,這是用戶從視圖中選擇請求的順序,而$answer['order']順序來自數據庫。所以我需要一個循環或什麼來比較這兩個..任何幫助..?謝謝。循環重複比較陣列

foreach($questions as $question) { 

    $question_answers = OrderingAnswer::where('question_id', $question->id) 
        ->where('deleted',0) 
        ->get() 
        ->toArray(); 
    $users_answers = $request->except('_token', 'test_id'); 

    $user_answer = $users_answers[ $question->id]; 

    // $user_answer ---> Array ([0] => 1 [1] => 4 [2] => 3 [3] => 2) 
    foreach ($question_answers as $answer) { 
    //$answer['order'] ---> 1 

    foreach ($user_answer as $key => $value) { 
     if ($answer['order'] == $value) { 
     echo "ok ===>" .$value . "<br>" ; 

     } else { 
     echo "no -------------------------------- >".$value . "<br>" ; 
     } 
    } 
    }   
+0

可以發佈這些列陣內的樣本2 - $ question_answers和$ user_answer和第三預期結果格式 – Farsay

+0

$ question_answers具有這樣的結果,如果我使用dd,陣列做到這一點:4 [▼ 0 =>數組:5 [▼ 「ID」=> 251 「question_id」=> 242 「文本」=> 「pytja 1」 「命令」=> 1 「已刪除」=> 0 ] 1 =>數組:5 $] 2 => array:5 [▶] 3 => array:5 [▶] ]並且$ user_answer具有此$ user_answer ---> Array([0] => 1 [1] => 4 [ 2] => 3 [3] => 2),我想要對於前1的$ user_answer的順序是==什麼是來自數據庫和回聲真實,否則我想顯示爲錯誤的問題,所以一個答案不正確的順序問題是錯誤的 – ylli

回答

0

我試過這個 - 它工作的很完美。 (這個問題真的很有趣)

這裏基本上我是比較多維數組值與單維數組值。它只會給你一些匹配的結果。

<?php 
$question_answers= array(
     array("id"=>251,'question_id'=>242,'order'=>1), 
     array("id"=>252,'question_id'=>243,'order'=>2) 
    ); 
$user_answers = array(1,4,3,2); 

// you can just use this part 
$question_answers = array_filter($question_answers, function($arr) use ($user_answers) { 
    return in_array($arr['order'], $user_answers); 
}); 

echo "<pre>"; 
print_r($question_answers); 
?>