0

I have a problem here, I want to combine 2 arrays into 1, I've tried using array_merge from php, and merge () from laravel but nothing works //$plucked is EAV database

$vendor = Vendor::find($id)->toArray();
        $vendor_detail = Vendor_detail::where('vendor_id',$id)->get();
        $plucked = $vendor_detail->pluck('vendor_name','vendor_value');

        $merged = array_merge($plucked, $vendor);

        // $merged = $vendor->merge($plucked)->all(); 
        dd($merged);

I think because the array is different, there array $plucked

#items: array:10 [▼
    "user_email" => "[email protected]"

  ]

and there my array in $vendor


array:15 [▼
  "vendor_id" => 39
  "province" => "ACEH"

]

the output that I want

$somearray =[
   "vendor_id" => 39
  "province" => "ACEH"
  "user_email" => "[email protected]"

]
2
  • what you want in here??expected result here? Commented Dec 12, 2019 at 9:44
  • @albus_severus there's my expected result $somearray =[ "vendor_id" => 39 "province" => "ACEH" "user_email" => "[email protected]" ] Commented Dec 12, 2019 at 9:48

4 Answers 4

1

Your $vendor is one associative array while $plucked is an array of arrays. Even if it has only one item it will be of index zero so you need to loop through $plucked and merge for each one.

$vendor = Vendor::find($id)->toArray();
$vendor_detail = Vendor_detail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_name','vendor_value');

$merged = [];
foreach($plucked as $p){
    $merged[] = array_merge($p, $vendor);
}
dd($merged);
Sign up to request clarification or add additional context in comments.

Comments

1
$vendor = Vendor::find($id);
$vendor_detail = Vendor_detail::select('vendor_id','province')->where('vendor_id',$id)->get()->toArray();

$data= array_merge($vendor,$vendor_detail);

Comments

1

I think you should use database join to get faster results.

$vendor = Vendor::join('vendor_details', 'vendors.id', '=', 'vendor_details.vendor_id')
    ->select('vendors.*', 'vendor_name','vendor_value')
    ->where('id', $id)
    ->first();

if ($vendor)  {
    $vendor = $vendor->toArray();
}

Comments

0
  $vendor_detail = Vendor_detail::where('vendor_id',$id)->get(); will give you a collection

as well as $plucked = $vendor_detail->pluck('vendor_name','vendor_value'); will give you a collection, so, either you can use collection merge or you may like to loop through one and add merge another as other answer is doing, but these are not array, you are getting collections.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.