1

I am receiving this data from the request:

array:2 [
  0 => array:3 [
    "from" => 0
    "to" => 5
    "earned" => 0
  ]
  1 => array:3 [
    "from" => 5
    "to" => 10
    "earned" => 1
  ]
]

I would like to add brand_id to each sub-array.

I know that I can merge a field into the request like:

$request->merge([
    'brand_id' => $brand_id,
]);

Which results in:

array:3 [
  0 => array:3 [
    "from" => 0
    "to" => 5
    "earned" => 0
  ]
  1 => array:3 [
    "from" => 5
    "to" => 10
    "earned" => 1
  ]
  "brand_id" => "1"
]

Where I want the result to be:

array:2 [
  0 => array:4 [
    "from" => 0
    "to" => 5
    "earned" => 0
    "brand_id" => "1"
  ]
  1 => array:4 [
    "from" => 5
    "to" => 10
    "earned" => 1
    "brand_id" => "1"
  ]
]

It would be nice if it was possible to do it like:

$request->merge([
    '*.brand_id' => $brand_id,
]);

Note: I have checked this How to replace nested array value inside the Laravel request using merge? but if I'm going to use foreach, I won't need to be doing request merge. Besides maybe there's something new with Laravel 8.

Adem Tepe
  • 61
  • 6

1 Answers1

0

Try below code. You can iterate each elements and merge. (assuming you are using a request object)

$mergedArray = array_map(function($element) use ($brand_id){ 
    return array_merge($element, ['brand_id' => $brand_id]); 
}, $request->all())
Kenath
  • 600
  • 5
  • 13
  • This is a nifty solution, I am applying it but I got an error: `Undefined variable: brand_id` Then I add `$brand_id` in anonymous function definition, this time got this error: `Too few arguments to function App\\Http\\Controllers\\ShiftBreakController::App\\Http\\Controllers\\{closure}(), 1 passed and exactly 2 expected`. Searching for usage of array_map this way. – Adem Tepe May 12 '21 at 12:10
  • 1
    Found right usage here https://stackoverflow.com/questions/27599767/array-map-and-pass-2-arguments-to-the-mapped-function-array-map-argument-3 and got `$brand_id` variable like `function($element) use ($brand_id)` If there is no better suggestion I will mark your answer accepted @Kenath – Adem Tepe May 12 '21 at 12:34
  • Sorry I forgot to add the use. I'll correct it now. – Kenath May 14 '21 at 06:13