模数与剩余laravel

时间:2019-08-02 16:22:55

标签: laravel laravel-5.8

我正在尝试从可正常工作的laravel数组设置4列。问题是您如何处理余数?在我的循环中,我最终得到了2个额外的div,它们在我的输出末尾为空。我要遍历10个项目,这将给我余下的2.5。这是我的代码。

<div class="serviceListingColumn">
     <ul>
         @foreach($serviceListings as $serviceListing)
           @if ($serviceListing->service_category == $services->title)
               <li class="serviceListingItem">{{$serviceListing->service_name}}</li>
           @endif
           @if($loop->iteration % 4 === 0)
               </ul>
                </div>
                <div class="serviceListingColumn">
                   <ul>
           @endif
        @endforeach
    </ul>

1 个答案:

答案 0 :(得分:1)

我建议将原始数组分块,然后循环。模板逻辑更容易。

// Use the Collection's group() functionality in your controller.
// Use collect() if it isn't a Collection already.

$array = collect($array)->chunk(4);

// Your template then doesn't need to worry about modulus,
// and can focus on displaying the chunked groups.

@foreach ($array as $group)
    <div class="serviceListingColumn">
        <ul>
            @foreach ($group as $serviceListing)
                <li class="serviceListingItem">{{ $serviceListing->service_name }}</li>
            @endforeach
        </ul>
    </div>
@endforeach