Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge two array value in laravel

I want to merge two array in laravel 5.3.I have variable '$type' which return

`Illuminate\Support\Collection Object ( [items:protected] => Array ( [1] => rinu )`

which is get from the query

$type0=DB::table('users')->where('name','=',$head)->pluck('name','id');

I want to merge with array $type1 which returns

Illuminate\Support\Collection Object ( [items:protected] => Array ( [2] => john ) ) 
Illuminate\Support\Collection Object ( [items:protected] => Array ( [3] => dinesh ) )
Illuminate\Support\Collection Object ( [items:protected] => Array ( [4] => mahesh ) ) 
Illuminate\Support\Collection Object ( [items:protected] => Array ( ) )

$type1=DB::table('users')->where('name','=',$head)->pluck('name','id');

I tried to merge and store it in $type0;

$type0=$type0->merge($type1);

It return wrong value

Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => rinu [1] => john ) ) 
Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => rinu [1] => john [2] => dinesh ) ) 
Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => rinu [1] => john [2] => dinesh [3] => mahesh ) ) 
Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => rinu [1] => john [2] => dinesh [3] => mahesh ) )`

enter code here
like image 844
user3386779 Avatar asked Feb 14 '26 13:02

user3386779


2 Answers

If you want to recieve merged array (and not collection), you can use toArray() and array_merge() functions:

$mergedArray = array_merge($type0->toArray(), $type1->toArray());
like image 84
Alexey Mezenin Avatar answered Feb 16 '26 02:02

Alexey Mezenin


You seem to have a Collection for each value. So you are probably fetching each value independently instead of in one go.

Your problem is probably solved by using whereIn instead of a number of wheres.

$result = DB::table('users')
            ->whereIn('name', ['John', 'Dinesh', 'Mahesh'])
            ->get();
like image 23
winkbrace Avatar answered Feb 16 '26 01:02

winkbrace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!