Laravel `array_pluck` on any key

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

Imagine what I have:

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

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

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

+5
source share
2 answers

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

The function only supports a one-dimensional array. It will look for keys in the array that match the second parameter; which in your case is "id". You will notice that the array you are looking for in your examples only has a key named users and not a name id .

Using $array['users'] means that pluck looks at this array and then finds keys with id for each element.

+4
source

You can use Laravel collections to achieve something similar.

 $data = collect($array['users']); $ids = $data->pluck('id'); return $ids; 
+1
source

Source: https://habr.com/ru/post/1234013/


All Articles