Home:ALL Converter>nested foreach loop, with php and laravel

nested foreach loop, with php and laravel

Ask Time:2015-08-29T23:18:56         Author:Michael Mendoza

Json Formatter

I am having problem with my nested foreach loop, I have this code of my controller retrieving the values of two columns in separate table in my database.

What I want is to compare each values against the other table vice versa,...

table1             table2
some column1       some column2 
 a                  b
 b                  b
 c                  c

My desired output would be if the values of two columns compare, if it is true then output "match" otherwise "mismatch".

Here the attempt, but it doesn't work, only the last item in both tables column are being compared. i think i am missing with my nested loops.

///snippet///

controller

$temp_answers = array();
$answers = array();

$temp_answers = Tempanswer::where('subject_id', $subject_id)
                             ->where('student_id', $student_id)
                             ->lists('temp_answer');

$answers = Question::where('subject_slug', $subject->slug)
                             ->lists('letteranswer');

foreach ($temp_answers as $temp_answer) {

    foreach ($answers as $answer) {
        if($answer == $temp_answer){
            $flag = 'match';
        }else 
            $flag = 'mismatch';
    }
    echo $flag.' ';

 }

Author:Michael Mendoza,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/32287577/nested-foreach-loop-with-php-and-laravel
Fake Face :

CMIIW.\nYou want to check table1 and table2 is match. So if its not match you will get message \"mismatch\"\n\nAssumption 1: if each data from table1 is compared with all data in table2.\n\nforeach ($temp_answers as $temp_answer) {\n\n foreach ($answers as $answer) {\n if($answer == $temp_answer){\n $flag = 'match';\n }else {\n $flag = 'mismatch';\n break;\n }\n }\n\n if($flag == 'mismatch'){\n break;\n } \n }\n\necho $flag;\n\n\nAssumption 2: Each table is compared by each row. I mean row1 table1 is compared with row1 table2 and than row2 table1 is compared with row2 table2.\n\n$flag='';\nforeach ($temp_answers as $key1=>$temp_answer) {\n foreach ($answers as $key2=>$answer) {\n if($key1 == $key2){\n if($answer == $temp_answer){\n $flag = $flag.'match ';\n }else {\n $flag = $flag.'mismatch ';\n }\n break;\n }\n }\n}\necho $flag;\n",
2015-08-29T15:36:34
yy