Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

556
Visualizações
Join 2 laravel collections

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 .

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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;
});
over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório

0

$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]);}

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda