Laravel 5 Merge an array

天大地大妈咪最大 提交于 2019-12-24 00:46:21

问题


I am trying to merge an array with an input from a form of a random string of numbers

In my form I have

<input type="text" name="purchase_order_number" id="purchase_order_number" value="{{ $purchase_order_number }}" />

And in the controller:

public function store(CandidateRequest $request)
{
    $candidateInput = Input::get('candidates');
    $purchaseOrderNumber = Input::get('purchase_order_number');

    foreach ($candidateInput as $candidate)
    {

        $data = array_merge($candidate, [$purchaseOrderNumber]);

        $candidate = Candidate::create($data);

        dd($data);

When I dd($data) it’s getting my purchase_order_number but as seen below but how can I assign it to that row in the table?

array:6 [▼
  "candidate_number" => "5645"
  "givennames" => "fgfgf"
  "familyname" => "dfgfg"
  "dob" => "01/01/2015"
  "uln" => "45565445"
  0 => "5874587"
]

Many thanks,


回答1:


I figured this out with some help but the answer is to add:

$data = array_merge($candidate, ['purchase_order_number' => $purchaseOrderNumber]);

Thanks to everyone else who tried to help :)




回答2:


You could try this,

$data = array_merge($candidate, compact('purchaseOrderNumber'));



回答3:


Another way to do this (the simplest I think) is to do a union of arrays

$candidate += ['purchase_order_number' => $purchaseOrderNumber]; 

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.




回答4:


Try this:

$data = [];

foreach ($candidateInput as $candidate)
    array_push($data,$candidate);

 array_merge($data,$purchaseOrderNumber);

 $candidate = Candidate::create($data);

 dd($data);



回答5:


 $data = array_merge(['item'=>$item->toArray()], ['chef' => $chef->toArray()]);


来源:https://stackoverflow.com/questions/33918311/laravel-5-merge-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!