Laravel 5合并两个多维数组

时间:2019-03-15 15:39:28

标签: arrays laravel array-merge

我要吸引两个数组一个用户和一个广告,我必须通过合并这两个数组来制作另一个,这样每五个用户之后我将得到一个广告。提前致谢。

1 个答案:

答案 0 :(得分:0)

我喜欢将Laravel的收藏用于这样的事情:

$users = range(0, 19);                      // users are numbers
$ads = range('a', 'd');                     // ads are letters

$users = collect($users);                   // create a Collection from the array
$ads = collect($ads);

$result = $users->chunk(5)                  // break into chunks of five
    ->map(function($chunk) use (&$ads){
        return $chunk->push($ads->shift()); // append an ad to each chunk
    })->flatten()                           // combine all the chunks back together
    ->toArray();                            // change the Collection back to an array

dump($result);

礼物:

array:24 [
  0 => 0
  1 => 1
  2 => 2
  3 => 3
  4 => 4
  5 => "a"
  6 => 5
  7 => 6
  8 => 7
  9 => 8
  10 => 9
  11 => "b"
  12 => 10
  13 => 11
  14 => 12
  15 => 13
  16 => 14
  17 => "c"
  18 => 15
  19 => 16
  20 => 17
  21 => 18
  22 => 19
  23 => "d"
]