Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel `array_pluck` on any key

Tags:

php

laravel

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.

like image 520
David Rodrigues Avatar asked Oct 19 '15 09:10

David Rodrigues


2 Answers

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.

like image 131
Ben Swinburne Avatar answered Nov 05 '22 03:11

Ben Swinburne


You can use Laravel collections to achieve something like this.

$data = collect($array['users']);
$ids = $data->pluck('id');
return $ids;
like image 4
Basit Avatar answered Nov 05 '22 03:11

Basit