Laravel 8 chunk() {#collection-method}

2021-07-14 14:08 更新

chunk 方法把集合分割成多個(gè)指定大小的較小集合:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->all();

// [[1, 2, 3, 4], [5, 6, 7]]

當(dāng)使用如 Bootstrap 那樣的柵格系統(tǒng)時(shí),該方法在 視圖 中相當(dāng)有用。想象一下你有個(gè)想在柵格顯示的 Eloquent 模型:

@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach 
    


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)