Reputation: 10896
I've got this code in my Laravel 5.6
controller:
$ads = Advertisement::actives();
$ports = Port::filter($filters)
->actives()
->paginate(28);
I would like to add every 4th
port one advertisement. How could I do this?
So result should be:
//Collection
[
//Port,
//Port,
//Port,
//Port
//Advertisement
//Port
//Port
//Port
//Port
//Advertisement
//etc...
]
Upvotes: 1
Views: 2437
Reputation: 111859
If each of your add contains the same code, you can do it like this:
$ports = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
$ads = 'ad';
$ports = $ports->chunk(4)->each->push($ads)->collapse();
This will give you:
Collection {#530 ▼
#items: array:14 [▼
0 => 1
1 => 2
2 => 3
3 => 4
4 => "ad"
5 => 5
6 => 6
7 => 7
8 => 8
9 => "ad"
10 => 9
11 => 10
12 => 11
13 => "ad"
]
}
But if in $ads
you have multiple ads, you need to use a bit longer notation:
$ports = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
$ads = ['ad1', 'ad2', 'ad3'];
$ports = $ports->chunk(4)->map(function($items, $key) use ($ads) {
return $items->push($ads[$key]);
})->collapse();
dd($ports);
This will give you:
Collection {#530 ▼
#items: array:14 [▼
0 => 1
1 => 2
2 => 3
3 => 4
4 => "ad1"
5 => 5
6 => 6
7 => 7
8 => 8
9 => "ad2"
10 => 9
11 => 10
12 => 11
13 => "ad3"
]
}
For reference you can take a look at Collections documentation
Upvotes: 1
Reputation: 1585
You can splice into a collection just like an array.
Something like...
$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);
Produces...
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"
]
}
Upvotes: 1
Reputation: 35337
Use the chunk method to pull chunks of 4 ports:
foreach ($ports->chunk(4) as $chunk) {
// chunk will be a collection of four ports, pull however you need
// then pull the next available ad
}
Upvotes: 1