Skip to content
Advertisement

Laravel `array_pluck` on any key

Is possible use something like array_pluck($array, 'users.*.id')?

Imagine that I have:

$array = [
    'users' => [
        [ 'id' => 1 ],
        [ 'id' => 2 ],
        [ 'id' => 3 ],
    ]
];

And I want get [1, 2, 3].

I tried something like: users.*.id, users.id and users..id, but nothing worked.

Advertisement

Answer

From Laravel 5.7, you may use the Arr::pluck() helper.

use IlluminateSupportArr;

Arr::pluck($array['users'], 'id')

Use array_pluck($array['users'], 'id')

The function only supports a single dimensional array. It will search for keys in the array which match the second parameter; which in your case is ‘id’. You’ll note that the array you’re searching in your examples only has a key named users and none with the name id.

Using $array['users'] means pluck looks through that array and subsequently finds keys named id on each element.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement