I couldn't find any collection method that could do this
Sep 4, 2019
8
Level 14
How to merge 2 collections together?
I have 2 collections that I would like to merge but the merge() method doesn't seem to do what I expect.
Collection one
$collection_one = collect([
'user_id' => 1,
'username' => johnive3,
'posts' => 569,
]);
// 0 => array:3 [
// "user_id" => 1
// "username" => "johnive3"
// "posts" => 569
// ],
// 1 => array:3 [
// "user_id" => 105
// "username" => "larry_one"
// "posts" => 81
// ],
// 2 => array:3 [
// "user_id" => 7
// "username" => "sally25"
// "posts" => 1
// ]
Collection two (added comments for each user)
$collection_two = collect([
'user_id' => 1,
'username' => johnive3,
'comments' => 12,
]);
// 0 => array:3 [
// "user_id" => 1
// "username" => "johnive3"
// "comments" => 12
// ],
// 1 => array:3 [
// "user_id" => 105
// "username" => "larry_one"
// "comments" => 84
// ],
// 2 => array:3 [
// "user_id" => 7
// "username" => "sally25"
// "comments" => 984
// ]
Expected result
[
'user_id' => 1,
'username' => johnive3,
'posts' => 569
'comments' => 12,
]
// 0 => array:3 [
// "user_id" => 1
// "username" => "johnive3"
// "posts" => 569
// "comments" => 12
// ],
// 1 => array:3 [
// "user_id" => 105
// "username" => "larry_one"
// "posts" => 81
// "comments" => 84
// ],
// 2 => array:3 [
// "user_id" => 7
// "username" => "sally25"
// "posts" => 8
// "comments" => 984
// ]
Level 13
@martinzeltin try this one, it will be grouped by username
<?php
$all = $collection_one->merge($collection_two)->groupBy('username', false)->map(function ($value, $key) {
return $all[$key] = array_merge(...$value);
});
result
Collection {#231 ▼
#items: array:3 [▼
"johnive3" => array:4 [▼
"user_id" => 1
"username" => "johnive3"
"posts" => 569
"comments" => 12
]
"larry_one" => array:4 [▼
"user_id" => 105
"username" => "larry_one"
"posts" => 81
"comments" => 84
]
"sally25" => array:4 [▼
"user_id" => 7
"username" => "sally25"
"posts" => 1
"comments" => 984
]
]
}
1 like
Please or to participate in this conversation.