-
-
Save adamwathan/a04873b44a1dcd0f2b4257168499162c to your computer and use it in GitHub Desktop.
toAssoc Collection Macro
This file contains hidden or 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' => 'adam@example.com', 'home_town' => 'Cambridge'], | |
| ['name' => 'David Hemphill', 'email' => 'david@example.com', 'home_town' => 'Fort Worth'], | |
| ['name' => 'Benjamin Milde', 'email' => 'benjamin@example.com', 'home_town' => 'Augsburg'], | |
| ]); | |
| $emailLookup = $people->map(function ($person) { | |
| return [$person['name'], $person['email']]; | |
| })->toAssoc(); | |
| // => [ | |
| // 'Adam Wathan' => 'adam@example.com', | |
| // 'David Hemphill' => 'david@example.com', | |
| // 'Benjamin Milde' => 'benjamin@example.com', | |
| // ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment