问题
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 theright-hand array
appended to theleft-hand array
; for keys that exist in both arrays, the elements from theleft-hand array
will be used, and the matching elements from theright-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