在foreach laravel中学习

时间:2018-07-06 05:29:48

标签: php laravel laravel-5

我将两个数组从控制器传递到视图,然后在值相同时选择要选择的选项。但我想在select中显示来自$ arr_1的所有数据。结果是我选择的数据重复。

 $arr_1=["1","2","3","4"];
    $arr_2=["1","2","4"];
    @foreach($arr_1 as $val)
       @foreach($arr_2 as $value)
          @if($val==$value)
             <option selected>{{$val}}</option>
          @else
             <option>{{$val}}</option>
          @endif
       @endforeach
    @endforeach

有什么解决办法吗?

1 个答案:

答案 0 :(得分:1)

无需两个foreach就可以完成

$arr_1=["1","2","3","4"];
$arr_2=["1","2","4"];
<select multiple>
    @foreach($arr_1 as $val)
        @if(in_array($val,$arr_2))
         <option val="{{$val}}" selected>{{$val}}</option>
        @else
         <option val="{{$val}}" >{{$val}}</option>
        @endif
    @endforeach
</select>

Demo