Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pluckMany dotted key support #248

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

sfinktah
Copy link
Contributor

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']);

@spatie-bot
Copy link

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 spatie-bot closed this Mar 1, 2024
@sfinktah
Copy link
Contributor Author

@spatie-bot Dear unhelpful bot, I cannot control the reactions of your masters.

@freekmurze freekmurze reopened this Mar 18, 2024
@freekmurze
Copy link
Member

Could you document this?

@sfinktah
Copy link
Contributor Author

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;
            }
// ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants