Laravel Collection - mapToDictionary method

1 month ago

kenmush

Code

$data = collect([
    ['team' => 'Gor Mahia F.C.', 'player_name' => 'Francis Kahata'],
    ['team' => 'Gor Mahia F.C.', 'player_name' => 'Jacques Tuyisenge'],
    ['team' => 'F.C. Kariobangi Sharks', 'player_name' => 'Henry Juma'],
    ['team' => 'F.C. Kariobangi Sharks', 'player_name' => 'Moses Mwangi'],
    ['team' => 'Kakamega Homeboyz FC', 'player_name' => 'Moses Chikati'],
    ['team' => 'Kakamega Homeboyz FC', 'player_name' => 'Allan Wanga'],
]);

$groups = $data->mapToDictionary(function ($item, $key) {
    return [$item['team'] => $item['player_name']];
});

Output

=> Illuminate\Support\Collection {#1954
     all: [
       "Gor Mahia F.C." => [
         "Francis Kahata",
         "Jacques Tuyisenge",
       ],
       "F.C. Kariobangi Sharks" => [
         "Henry Juma",
         "Moses Mwangi",
       ],
       "Kakamega Homeboyz FC" => [
         "Moses Chikati",
         "Allan Wanga",
       ],
     ],
   }
HELO: Local email testing for your desktop!