Laravel 切片在集合中

Laravel slice in collection

我的 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...
]

使用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
}

可以像数组一样拼接成集合

类似...

  $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"
  ]  
}

如果你的每一个添加都包含相同的代码,你可以这样做:

$ports = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);

$ads = 'ad';

$ports = $ports->chunk(4)->each->push($ads)->collapse();

这会给你:

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"
  ]
}

但是如果在 $ads 中有多个广告,则需要使用更长的符号:

$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);

这会给你:

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"
  ]
}

作为参考,您可以查看 Collections documentation