Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jackFlick's avatar

Laravel - Get saved ID of merged array

I was able to combine the decoded request into an array but now I need to get the ID of the saved request.

Here's how I combined the array

$option= [
  0 => '"["Option 1", "Option 2", "Option 3"]"',
  1 => '"["Option 1.1", "Option 1.2"]"'
];
foreach($arr as &$a) $a = json_decode(trim($a, '"'), true);
var_dump($arr);
var_dump([0=>array_merge(... $arr)]);

Output

array:5 [
  0 => "Option 1"
  1 => "Option 2"
  2 => "Option 3"
  3 => "Option 1.1"
  4 => "Option 1.2"
]

I have 2 tables Choices and ChoicesFiles

I need to have the Choices ID to be included in the output so I can insert it to the ChoicesFiles

Desired Output

[
  0 => 	
[
		id: 10,
		option: "Option 1",
		]
  1 => 
		[
		id: 10,
		option: "Option 2",
		]

  2 => 
		[
		id: 10,
		option: "Option 3",
		]

  3 => 
		[
		id: 11,
		option: "Option 1.1",
		]
  4 => 
		[
		id: 11,
		option: "Option 4",
		]
]

Hope someone can help me achieve this output.

0 likes
2 replies
a4ashraf's avatar
a4ashraf
Best Answer
Level 33

@jvbalcita

this may help you with your desire result

$collection = collect(['product_id' => 1, 'price' => 100]);

$merged = $collection->mergeRecursive(['product_id' => 2, 'price' => 200, 'discount' => false]);

$merged->all();

// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]

for more detail see the documentation

https://laravel.com/docs/6.x/collections#method-merge

jackFlick's avatar

@a4ashraf

What if they are on a different array?

$idArray = [
0 => 1,
1 => 2,
]
$option= [
  0 => '"["Option 1", "Option 2", "Option 3"]"',
  1 => '"["Option 1.1", "Option 1.2"]"'
];

Please or to participate in this conversation.