简体   繁体   中英

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.

Perhaps a more laravelish way;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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