php - 如何在 Laravel 5 中使用 php 以特定模式设置 foreach 循环中的元素
问题描述
如您所见,我从数据库中获取了一些帖子。我想为上述模式的帖子赋予不同的风格。
我已经设法使用刀片为第一篇文章赋予了不同的风格$loop iteration
。顺便说一句,我使用的是 laravel 5。我想赋予相同的风格post3
post 4
post 7
post 8
并遵循这种模式。我如何使用 php 来实现这一点?
解决方案
你可以在你的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
推荐阅读
- python - 将货币插入 SQL 数据库
- ios - NSMutableArray 新的协议类型
- python - 将记录从第一个 Django 模型移动到第二个,然后从第一个删除它
- laravel - Laravel 循环嵌套 JSON
- react-native - 为什么我不能在 React Native 中共享音频文件?
- node.js - node.js 中的笑话测试失败,显示 Matcher 错误
- python - Python:存储数字键值对的最佳方式是什么?
- javascript - Android Webview 崩溃并出现 GL 错误:GL_INVALID_VALUE
- python - 如何遍历文本文件目录、提取特定行并写入 csv
- azure-devops - azure devops 上的计划构建作业停止计划新构建