-
-
Save adamwathan/a04873b44a1dcd0f2b4257168499162c to your computer and use it in GitHub Desktop.
toAssoc Collection Macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Given a collection of pairs, turn it into a key => value collection | |
Collection::macro('toAssoc', function () { | |
return $this->reduce(function ($items, $pair) { | |
list($key, $value) = $pair; | |
return $items->put($key, $value); | |
}, new static); | |
}); | |
$people = collect([ | |
['name' => 'Adam Wathan', 'email' => '[email protected]', 'home_town' => 'Cambridge'], | |
['name' => 'David Hemphill', 'email' => '[email protected]', 'home_town' => 'Fort Worth'], | |
['name' => 'Benjamin Milde', 'email' => '[email protected]', 'home_town' => 'Augsburg'], | |
]); | |
$emailLookup = $people->map(function ($person) { | |
return [$person['name'], $person['email']]; | |
})->toAssoc(); | |
// => [ | |
// 'Adam Wathan' => '[email protected]', | |
// 'David Hemphill' => '[email protected]', | |
// 'Benjamin Milde' => '[email protected]', | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment