Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Created May 9, 2016 16:43
Show Gist options
  • Save adamwathan/a04873b44a1dcd0f2b4257168499162c to your computer and use it in GitHub Desktop.
Save adamwathan/a04873b44a1dcd0f2b4257168499162c to your computer and use it in GitHub Desktop.
toAssoc Collection Macro
<?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