Laravel 8 Loop 變量

2021-07-02 17:20 更新

循環(huán)時(shí),循環(huán)內(nèi)部可以使用 $loop 變量。該變量提供了訪問一些諸如當(dāng)前的循環(huán)索引和此次迭代是首次或是末次這樣的信息的方式:

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach

如果您在嵌套循環(huán)中,您可以使用循環(huán)的 $loop 的變量的 parent 屬性訪問父級循環(huán):

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.
        @endif
    @endforeach
@endforeach

$loop 變量還包含各種各樣有用的屬性:

屬性 描述
$loop->index 當(dāng)前迭代的索引(從 0 開始)。
$loop->iteration 當(dāng)前循環(huán)的迭代次數(shù)(從 1 開始)。
$loop->remaining 循環(huán)剩余的迭代次數(shù)。
$loop->count 被迭代的數(shù)組的元素個(gè)數(shù)。
$loop->first 當(dāng)前迭代是否是循環(huán)的首次迭代。
$loop->last 當(dāng)前迭代是否是循環(huán)的末次迭代。
$loop->even 當(dāng)前循環(huán)的迭代次數(shù)是否是偶數(shù)。
$loop->odd 當(dāng)前循環(huán)的迭代次數(shù)是否是奇數(shù)。
$loop->depth 當(dāng)前循環(huán)的嵌套深度。
$loop->parent 嵌套循環(huán)中的父級循環(huán)。
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)