PHP Laravel break foreach loop 2 times

There are three foreach loop and on the last foreach loop there is an if condition,

foreach ($candidate_data as $cd) {
        $edu_data=DB::table('applicant_edu_info')
        ->where('applicant_id',$cd->ap_id)
        ->get();
            foreach($edu_data as $ed){
                foreach($neededDegree as $nd){
                    if($neededDegree->edu_degree_id==$ed->edu_degree_id){
                        $education_data[$cd->ap_id]=$neededDegree->name;

                    }
                }
            }
    }

what I need is , If the condition is true then I want to break two loops and continue running from the first foreach loop. Please help.


In PHP you can use the optional param of break.

Use break 2;

foreach ($candidate_data as $cd) {
        $edu_data=DB::table('applicant_edu_info')
        ->where('applicant_id',$cd->ap_id)
        ->get();
            foreach($edu_data as $ed){
                foreach($neededDegree as $nd){
                    if($neededDegree->edu_degree_id==$ed->edu_degree_id){
                        $education_data[$cd->ap_id]=$neededDegree->name;
                         break 2;

                    }
                }
            }
    }

break 2 will break two loops.

Docs: http://php.net/manual/en/control-structures.break.php


You can use goto which used to jump to another section in the program.

foreach ($candidate_data as $cd) {
    $edu_data=DB::table('applicant_edu_info')
    ->where('applicant_id',$cd->ap_id)
    ->get();
        foreach($edu_data as $ed){
            foreach($neededDegree as $nd){
                if($neededDegree->edu_degree_id==$ed->edu_degree_id){
                    $education_data[$cd->ap_id]=$neededDegree->name;
                    goto targetLocation;

                }
            }
        }
      targetLocation:
}

Using goto you can set your target anywhere you want.

链接地址: http://www.djcxy.com/p/53078.html

上一篇: Laravel Foreach:未定义变量

下一篇: PHP Laravel 2次破解foreach循环