[英]Laravel merge arrays inside an array
我有这样的结果
array:2 [
0 => array:5 [
0 => 3
1 => 7
2 => 8
3 => 9
4 => 10
]
1 => array:1 [
0 => 216
]
]
我想要这样:
array:6 [
0 => 3
1 => 7
2 => 8
3 => 9
4 => 10
5 => 216
]
我应该如何更改我的代码?
$barcodes = [];
foreach($request->input('serials') as $serial)
{
if(!empty($serial['barcode_id'])) {
if($serial['amount'] > 1) {
$barcodes[] = Barcode::where('sold', true)->take($serial['amount'])->pluck('id')->toArray(); // returned `0 => array:5 [`
} else {
$barcodes[] = Barcode::where('sold', true)->where('serial_number', $serial['barcode_id'])->orWhere('u_serial_number', $serial['barcode_id'])->pluck('id')->toArray(); // returned `1 => array:1 [`
}
}
}
dd($barcodes);
您可以直接在循环中执行此操作:
$barcodes = [];
foreach($request->input('serials') as $serial)
{
if(!empty($serial['barcode_id'])) {
if($serial['amount'] > 1) {
$barcodes = array_merge($barcodes, Barcode::where('sold', true)->take($serial['amount'])->pluck('id')->toArray());
} else {
$barcodes = array_merge($barcodes, Barcode::where('sold', true)->where('serial_number', $serial['barcode_id'])->orWhere('u_serial_number', $serial['barcode_id'])->pluck('id')->toArray());
}
}
}
解决方案是使用...
运算符合并我的内部数组
array_merge(...$barcodes)
并完成了这项工作。
也许是一种更幼稚的方式;
//Bring in Arr facade
use Illuminate\Support\Arr;
//Then
Arr::flatten($barcodes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.