I have 2 arrays and I want to merge them. (I can merge them) but I also need to include their unique keys in merged results and that part I cannot achieve.
sample
$prices = [
['112802' => "500000"],
['113041' => "1000000"],
];
$notes = [
['112802' => "note 2"],
['113041' => "note 1"],
];
$collection = collect($prices);
$zipped = $collection->zip($notes);
$zipped->toArray();
Unique keys are
112802
and113041
.
When I merge my array all I get is this:
[
[
"1000000",
"note 1"
],
[
"500000",
"note 2"
]
]
What I’m looking for is like this:
[
[
"id" => "112802",
"price" => "500000",
"note" => "note 2",
],
[
"id" => "113041",
"price" => "1000000",
"note" => "note 1",
]
}]
any suggestion?
2
Answers
This does what you want with the data you provide.
NOTE it will only work if your 2 arrays are the same size and the the keys are in the same order.
If this data comes from a database, it is likely it could have been produced in the format you actually wanted rather than having to fiddle with the data post fetch.
RESULT
Here’s another solution using some of Laravel’s Collection methods.
It’s not the most elegant, but it can be a starting point for you.
Below is the
$result
(called usingdd()
).It’s achieved by extracting the ID so that the zip can join there, but then we need a little hack with the
map
andmapWithKeys
in the$result
.That’s just because otherwise each element in
$result
will still have two separate arrays for$prices
and$notes
.