Created
February 19, 2017 15:54
-
-
Save nigelheap/4ec7e43c71a75c309caa353fa42d5d95 to your computer and use it in GitHub Desktop.
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 | |
use Illuminate\Support\Collection; | |
if (! Collection::hasMacro('pluckWithKey')) { | |
/* | |
* Keeps the key from the original array while plucking the value from the child array. | |
* Useful for pulling keyed config form the config files | |
* | |
* Example: If you have this: | |
* | |
* $services = [ | |
* 'service1' => ['name' => 'Service 1', 'url' => 'http://something.com'], | |
* 'service2' => ['name' => 'Service 2', 'url' => 'http://somethingelse.com'], | |
* ] | |
* | |
* And you run | |
* | |
* collect($services)->pluckWithKey('name'); | |
* | |
* It will return: | |
* | |
* [ | |
* 'service1' => 'Service 1', | |
* 'service2' => 'Service 2', | |
* ] | |
* | |
* | |
* @param string $valueKey | |
* | |
* @return array | |
*/ | |
Collection::macro('pluckWithKey', function ($valueKey) { | |
return $this->map(function($item) use ($valueKey){ | |
return array_key_exists($valueKey, $item) ? $item[$valueKey] : null; | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment