Let's assume I have the following multidimensional array (retrieved from MySQL or a service):
array(
array(
[id] => xxx,
[name] => blah
),
array(
[id] => yyy,
[name] => blahblah
),
array(
[id] => zzz,
[name] => blahblahblah
),
)
Can we get an array of id
s in one "built-in" php function call? or one line of code?
I am aware of the traditional looping and getting the value but I don't need this:
foreach($users as $user) {
$ids[] = $user['id'];
}
print_r($ids);
Maybe some array_map()
and call_user_func_array()
can do the magic.
This question is related to
php
You can also use array_reduce()
if you prefer a more functional approach
For instance:
$userNames = array_reduce($users, function ($carry, $user) {
array_push($carry, $user['name']);
return $carry;
}, []);
Or if you like to be fancy,
$userNames = [];
array_map(function ($user) use (&$userNames){
$userNames[]=$user['name'];
}, $users);
This and all the methods above do loop behind the scenes though ;)
If id
is the first key in the array, this'll do:
$ids = array_map('current', $users);
You should not necessarily rely on this though. :)
Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Solution by @phihag will work flawlessly in PHP starting from PHP 5.3.0, if you need support before that, you will need to copy that wp_list_pluck.
In Wordpress there is a function called wp_list_pluck If you're using Wordpress that solves your problem.
PHP < 5.3If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here
Source: Stackoverflow.com