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.
From Laravel 5.7, you may use the Arr::pluck()
helper.
use Illuminate\Support\Arr;
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.
You can use Laravel collections to achieve something like this.
$data = collect($array['users']);
$ids = $data->pluck('id');
return $ids;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With