Blade中的过滤数组
Filtering array in Blade
我需要展示某张图片。如果图片 is_primary
属性 已填充且为真,那么我需要显示该图片。否则,我应该只显示第一个。这是我的代码。它不起作用,我同时看到 is_primary
图片和第一张。我做错了什么?
@php
$check = 0
@endphp
@foreach ($ad->photos as $photo)
@if ($photo->is_primary == true)
<img src="{{$photo->filename}}" alt="{{$ad->name}}" class="card-image">
@php
$check = 1
@endphp
@endif
@endforeach
@if ($check > 0)
<img src="{{$ad->photos->first()->filename}}" alt="{{$ad->name}}" class="card-image">
@endif
你逻辑有问题。如果 is_primary
为真,则显示图像并将标志变量设置为 1。循环结束时你正在检查 $check > 0
所以当 $check =1
你需要添加条件 $check == 0
时它是真的
@php
$check = 0
@endphp
@foreach ($ad->photos as $photo)
@if ($photo->is_primary == true)
<img src="{{$photo->filename}}" alt="{{$ad->name}}" class="card-image">
@php
$check = 1
@endphp
@endif
@endforeach
@if ($check == 0)
<img src="{{$ad->photos->first()->filename}}" alt="{{$ad->name}}" class="card-image">
@endif
或者您可以检查 != 1
@if ($check != 1)
<img src="{{$ad->photos->first()->filename}}" alt="{{$ad->name}}" class="card-image">
@endif
我需要展示某张图片。如果图片 is_primary
属性 已填充且为真,那么我需要显示该图片。否则,我应该只显示第一个。这是我的代码。它不起作用,我同时看到 is_primary
图片和第一张。我做错了什么?
@php
$check = 0
@endphp
@foreach ($ad->photos as $photo)
@if ($photo->is_primary == true)
<img src="{{$photo->filename}}" alt="{{$ad->name}}" class="card-image">
@php
$check = 1
@endphp
@endif
@endforeach
@if ($check > 0)
<img src="{{$ad->photos->first()->filename}}" alt="{{$ad->name}}" class="card-image">
@endif
你逻辑有问题。如果 is_primary
为真,则显示图像并将标志变量设置为 1。循环结束时你正在检查 $check > 0
所以当 $check =1
你需要添加条件 $check == 0
@php
$check = 0
@endphp
@foreach ($ad->photos as $photo)
@if ($photo->is_primary == true)
<img src="{{$photo->filename}}" alt="{{$ad->name}}" class="card-image">
@php
$check = 1
@endphp
@endif
@endforeach
@if ($check == 0)
<img src="{{$ad->photos->first()->filename}}" alt="{{$ad->name}}" class="card-image">
@endif
或者您可以检查 != 1
@if ($check != 1)
<img src="{{$ad->photos->first()->filename}}" alt="{{$ad->name}}" class="card-image">
@endif