Home > Blockchain >  Join 2 laravel collections
Join 2 laravel collections

Time:11-24

I have 2 collections :

$collection1 = [ 
{ name : "aaa" , score : 10 },
{ name : "bbb" , score : 20 }
];
$collection2 = [ 
{ name : "aaa" , score : 30 },
{ name : "bbb" , score : 10 }
];

and I want to join them to get the following result :

$collection3 = [ 
{ name : "aaa" , score : 40 },
{ name : "bbb" , score : 30 }
]

merge() and union() didn't do the job for me .

CodePudding user response:

Combine the collections, group by the name and sum the score. This can be done like so with collections in Laravel. Note that group by returns a collection of the grouped data.

$collection1->concat($collection2);

$collection1->groupBy('name')->map(function ($scores) {
    $score = $scores->first();

    $score['score'] = $scores->sum('score');

    return $score;
});

CodePudding user response:

it can be achieve by laravel collection map() and where() function

$collection1 = collect([
    [
        "name" => "aaa",
        "score" => 10
    ],
    [
        "name" => "bbb",
        "score" => 20
    ]
]);
$collection2 = collect([
    [
        "name" => "aaa",
        "score" => 30
    ],
    [
        "name" => "bbb",
        "score" => 10
    ]
]);

$collection3 = $collection1->map(function ($item) use ($collection2) {
        $found = $collection2->where('name', $item['name']);
        if ($found) {
            $item['score'] = $item['score']   $found->first()['score'];
        }
        return $item;
    });

dd($collection3);

This is the result https://phpsandbox.io/n/soft-flower-ap1e-vo2xy

CodePudding user response:

$collection = collect();$collection->merge(['col1' => $col1, 'col2' => $col2 ]); OR $states = [ 'Delhi', 'Tamil Nadu', 'Uttar Pradesh']; foreach ($states as $state) { $data = DB::table('user')->select('user.*') ->where("user.city", $state)->where('user.status', 1)->get(); if (!empty($data[0])) $stateUser = $stateUser->merge([$state => $data]);}

  • Related