简体   繁体   English

Laravel 合并数组内的数组

[英]Laravel merge arrays inside an array

I have such result我有这样的结果

array:2 [
  0 => array:5 [
    0 => 3
    1 => 7
    2 => 8
    3 => 9
    4 => 10
  ]
  1 => array:1 [
    0 => 216
  ]
]

And I want to have it like this:我想要这样:

array:6 [
    0 => 3
    1 => 7
    2 => 8
    3 => 9
    4 => 10
    5 => 216
]

How should I change my code?我应该如何更改我的代码?

$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);

You can do it directly in the loop:您可以直接在循环中执行此操作:

$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());
        }
    }
}

Solved解决了

the solution was using ... operator to merge my inside arrays解决方案是使用...运算符合并我的内部数组

array_merge(...$barcodes) and that did the job. array_merge(...$barcodes)并完成了这项工作。

Perhaps a more laravelish way;也许是一种更幼稚的方式;

//Bring in Arr facade
use Illuminate\Support\Arr;
//Then
Arr::flatten($barcodes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM