[英]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.