[英]Filtering array in Blade
I need to show a certain picture. 我需要显示一张图片。 If a picture has
is_primary
property filled and true then I need to show that picture. 如果一张图片具有
is_primary
属性已填充且为true,则需要显示该图片。 Otherwise, I should just display whatever is first. 否则,我应该只显示第一个。 Here is my code.
这是我的代码。 It doesn't work, I see both
is_primary
picture and first. 它不起作用,我同时看到了
is_primary
图片和first。 What am I doing wrong? 我究竟做错了什么?
@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
You have issue in you logic. 您的逻辑存在问题。 If
is_primary
is true you are displaying image and set flag variable to 1 . 如果
is_primary
为true,则显示图像,并将flag变量设置为1 。 And end of loop you are checking $check > 0
so its true when $check =1
you need to add condition $check == 0
循环结束时,您正在检查
$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
OR you can check != 1 或者您可以检查!= 1
@if ($check != 1)
<img src="{{$ad->photos->first()->filename}}" alt="{{$ad->name}}" class="card-image">
@endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.