laravel-collection-macros
laravel-collection-macros copied to clipboard
pluckMany dotted key support
To bring pluckMany
inline with various other pluck
implementations, including Collections::pluck
(Arr::pluck
), this allows the specification of dotted keys.
e.g.,
$ar = collect($chunk)
->pluckMany(['id', 'handle', 'variants.edges.0.node.sku', 'spaghetti']);
Dear contributor,
because this pull request seems to be inactive for quite some time now, I've automatically closed it. If you feel this pull request deserves some attention from my human colleagues feel free to reopen it.
@spatie-bot Dear unhelpful bot, I cannot control the reactions of your masters.
Could you document this?
Dear human :)
How would you like it documented, it's how lodash (though not underscore) behaves when a string key is specified to _.map
It's also how Collection::pluck operates. If you would permit me a slight rudeness, you should be documenting why your pluckMany doesn't operated on dotted values.
public static function pluck($array, $value, $key = null)
{
$results = [];
[$value, $key] = static::explodePluckParameters($value, $key);
foreach ($array as $item) {
$itemValue = data_get($item, $value);
function data_get($target, $key, $default = null)
{
if (is_null($key)) {
return $target;
}
$key = is_array($key) ? $key : explode('.', $key);
foreach ($key as $i => $segment) {
unset($key[$i]);
if (is_null($segment)) {
return $target;
}
if ($segment === '*') {
if ($target instanceof Collection) {
$target = $target->all();
} elseif (! is_iterable($target)) {
return value($default);
}
$result = [];
foreach ($target as $item) {
$result[] = data_get($item, $key);
}
return in_array('*', $key) ? Arr::collapse($result) : $result;
}
// ...
Great macro. When will be merged 👀
Thanks!