我有这个代码,我想比较来自db的数据和一个用户选择但似乎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 :(得分: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);
?>