Laravel 5 Merge an array
Asked Answered
A

7

8

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,

Adriaadriaens answered 25/11, 2015 at 13:54 Comment(1)
Does this answer your question? Create associative array from Foreach Loop PHPPastrami
A
21

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 :)

Adriaadriaens answered 25/11, 2015 at 14:19 Comment(0)
I
11

try this:

use Illuminate\Support\Arr;
$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

more: laravel helpers

Inferential answered 12/10, 2020 at 12:32 Comment(1)
Hey! Thank you for taking the time and answering the question! Can you write more than your code and explain why it works?Grandmother
T
4

You could try this,

$data = array_merge($candidate, compact('purchaseOrderNumber'));
Tie answered 25/11, 2015 at 14:20 Comment(0)
A
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.

Alanis answered 21/2, 2018 at 6:26 Comment(0)
A
3
 $data = array_merge(['item'=>$item->toArray()], ['chef' => $chef->toArray()]);
Antiknock answered 9/10, 2018 at 7:59 Comment(1)
While this might solve the problem, it is better to provide some explanation of what you are doing.Donall
M
1
$data = $firstArray->merge($secondArray);
Misapprehension answered 15/7, 2020 at 19:31 Comment(1)
merge method is part of the Illuminate\Support\Collection class. So, to use it $firstArray must be a collectionHoneyed
H
0

Try this:

$data = [];

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

 array_merge($data,$purchaseOrderNumber);

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

 dd($data);
Hopeh answered 25/11, 2015 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.