通过 blade (Laravel) 中的迭代计数

Counting through the iterations in blade (Laravel)

我想知道我是否可以为数组的每次迭代做一个 if 语句。这样我就可以根据用户数量用“,”或“&”标点符号。

@foreach ($copy as $user => $value) 
@if ($user == 0)
{{$value->username}}
@endif
@if ($user == 1)
, {{$value->username}}
@endif
@if ($user == 2)
, {{$value->username}}
@endif
@if ($user == 3)
& {{$value->username}}
@endif
@endforeach

如果有 4 个用户,上面的代码会正确标点符号,但如果我的用户少于 4 个怎么办?例如,如果有 3 个用户,我如何将“&”移动到第 3 个用户?

遇到此类问题时,请尝试找到最佳解决方案。在这种情况下,您可以确定除了两个地方之外的所有地方都需要逗号,一个地方需要 & 符号。因此,不是为每个数组索引设置条件,而是应该为逗号放置一个条件,为与符号放置一个条件:

@foreach ($copy as $user => $value) 
    {{$value->username}}

    // Place commas after all but the last two items
    @if ($user < count($copy) - 2)
        ,
    @endif

    // Place an ampersand before the last item
    @if ($user == count($copy) - 2)
        &amp;
    @endif
@endforeach

这适用于任何大小的列表。