Skip to content

Instantly share code, notes, and snippets.

@nigelheap
Created February 19, 2017 15:54
Show Gist options
  • Save nigelheap/4ec7e43c71a75c309caa353fa42d5d95 to your computer and use it in GitHub Desktop.
Save nigelheap/4ec7e43c71a75c309caa353fa42d5d95 to your computer and use it in GitHub Desktop.
<?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