arrays - Laravel 5 合并两个多维数组
问题描述
我得到两个数组一个用户和一个广告我必须通过合并这两个数组来制作另一个数组,这样每五个用户我就会得到一个广告。提前致谢。
解决方案
我喜欢使用 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"
]
推荐阅读
- sql - 普遍的日期比较
- asp.net-mvc - 如何将数据从局部视图传递到主控制器 - ASP.NET MVC
- rxjs - 如何根据每个值的可观察属性过滤掉可观察值
- css - 自定义引导程序 4 CDN
- nodemon - 如何从 package.json 在 windows 中运行 nodemon
- javascript - 使用 vanilla JS 重新计算更改事件的数字
- stm32 - STM3 USART+DMA 收不到
- react-native - 键盘打开时滚动视图(React Native / Expo)
- python - 程序内存泄漏(熊猫数据框)
- c# - 如何以编程方式创建新的本地 SQL Server 实例?