Laravel 5合并两个多维数组

问题描述 投票:0回答:1

我得到两个阵列一个用户和一个广告我必须通过合并这两个阵列来制作另一个广告,以便在每五个用户之后我将获得一个广告。提前致谢。

arrays laravel array-merge
1个回答
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"
]
© www.soinside.com 2019 - 2024. All rights reserved.