laravel刀片中嵌套的foreach循环

时间:2018-12-19 08:18:16

标签: php laravel

我在laravel的刀片中嵌套了foreach,但是所有记录在我的select选项中压缩两次,这是我的代码:

@foreach($user as $user)
    @foreach($user_renter as $last_user_renter)
        @if($user->id == $last_user_renter->user_id)
           <option value="{{ $user->id }}" selected>
              {{ $user->name }} {{ $user->family }} - {{ $user->email }}
           </option>
        @else
           <option value="{{ $user->id }}">
              {{ $user->name }} {{ $user->family }} - {{ $user->email }}
           </option>
        @endif
    @endforeach
@endforeach

现在有没有办法将它们压缩一次?

1 个答案:

答案 0 :(得分:0)

尝试按以下所示将user_renter更改为数组

$user_renter = array(
   array(
    'name' => 'flash',
    'id' => 1
),
array(
    'name' => 'zoom',
    'id' => 2
),
array(
    'name' => 'snart',
    'id' => 3
)
 );

@foreach($users as $user) <?php $key = array_search($user->id, array_column($user_renter, 'id')); ?> <option value="{{ $user->id }}" @if(is_int($key)) selected @endif> {{ $user->name }} {{ $user->family }} - {{ $user->email }} </option> @endforeach