首页 > 解决方案 > 如何在 Laravel 5 中使用 php 以特定模式设置 foreach 循环中的元素

问题描述

请看一下这张图片在此处输入图像描述

如您所见,我从数据库中获取了一些帖子。我想为上述模式的帖子赋予不同的风格。

我已经设法使用刀片为第一篇文章赋予了不同的风格$loop iteration。顺便说一句,我使用的是 laravel 5。我想赋予相同的风格post3 post 4 post 7 post 8并遵循这种模式。我如何使用 php 来实现这一点?

标签: phplaravelloops

解决方案


你可以在你的foreach指令中这样做:

@foreach ($blocks as $index => $block)
    @if ($index == 0)
        @include('full')
    @elseif ($index % 4 < 2)
        @include('gray')
    @else
        @include('blue')
    @endif
@endforeach

所以基本上,它将采用索引的模数,并检查它是否低于 1。这将给出以下灰色方块:

1, 4, 5, 8

由于它是索引(零基数),它将以灰色显示以下块:

2, 5, 6, 9

然后其他块将是蓝色的。


例子

$range = range(1, 9);

foreach ($range as $index => $block) {
    echo sprintf('Post %s: ', $index + 1);

    if ($index == 0) {
        echo 'full';
    } elseif ($index % 4 < 2) {
        echo 'gray';
    } else {
        echo 'blue';
    }
    echo '<br>';
}

结果

Post 1: full
Post 2: gray
Post 3: blue
Post 4: blue
Post 5: gray
Post 6: gray
Post 7: blue
Post 8: blue
Post 9: gray

推荐阅读