我的Laravel 5.6
控制器中有以下代码:
$ads = Advertisement::actives();
$ports = Port::filter($filters)
->actives()
->paginate(28);
我想为每个4th
端口添加一个广告。我该怎么办?
所以结果应该是:
//Collection
[
//Port,
//Port,
//Port,
//Port
//Advertisement
//Port
//Port
//Port
//Port
//Advertisement
//etc...
]
答案 0 :(得分:1)
使用chunk方法提取4个端口的块:
foreach ($ports->chunk(4) as $chunk) {
// chunk will be a collection of four ports, pull however you need
// then pull the next available ad
}
答案 1 :(得分:1)
您可以像数组一样拼接到集合中。
类似...
$ads = collect(['ad1','ad2','ad3','ad4']);
$ports = collect([
"port 1",
"port 2",
"port 3",
"port 4",
"port 5",
"port 6",
"port 7",
"port 8",
"port 9",
"port10",
"port11"
]);
for($i=4; $i<=$ports->count(); $i+=5) {
$ports->splice($i, 0, $ads->shift());
}
// tack on the remaining $ads at the end
// (I didn't check if there actually are any).
$everyone=$ports->concat($ads);
dd($everyone);
生产...
Collection {#480 ▼
#items: array:15 [▼
0 => "port 1"
1 => "port 2"
2 => "port 3"
3 => "port 4"
4 => "ad1"
5 => "port 5"
6 => "port 6"
7 => "port 7"
8 => "port 8"
9 => "ad2"
10 => "port 9"
11 => "port10"
12 => "port11"
13 => "ad3"
14 => "ad4"
]
}