How to get an array of a certain "key" in a multidimensional array without a loop

Suppose I have the following multidimensional array (extracted from MySQL or a service):

array( array( [id] => xxx, [name] => blah ), array( [id] => yyy, [name] => blahblah ), array( [id] => zzz, [name] => blahblahblah ), ) 

Is it possible to get an id array in one "built-in" php function call? or one line of code?
I know about the traditional loop and get the value, but I don't need it:

 foreach($users as $user) { $ids[] = $user['id']; } print_r($ids); 

Perhaps some array_map() and call_user_func_array() can do the magic.

+61
php
Nov 03 '11 at 12:01
source share
3 answers

With php 5.5 you can use array_column :

 $ids = array_column($users, 'id'); 

With php 5.3 you can use array_map with an anonymous function, for example:

 $ids = array_map(function ($ar) {return $ar['id'];}, $users); 

Prior to (Technically php 4.0.6 +) you should create an anonymous function with create_function instead:

 $ids = array_map(create_function('$ar', 'return $ar["id"];'), $users); 
+148
Nov 03 2018-11-11T00:
source share

PHP 5.5+

Starting with PHP5.5 + you have array_column () , which makes everything below deprecated.

PHP 5.3+

$ids = array_map(function ($ar) {return $ar['id'];}, $users);

The @phihag solution will work flawlessly in PHP, starting with PHP 5.3.0, if you need support before that, you will need to copy this wp_list_pluck file.

PHP <5.3

Wordpress 3.1+

Wordpress has a feature called wp_list_pluck if you use Wordpress that solves your problem.

PHP <5.3

If you are not using Wordpress because the code is open source, you can copy the code into your project (and rename the function to something you like best, like array_pick). View source here

+7
Aug 21 '13 at 15:55
source share

If id is the first key in the array, this will do:

 $ids = array_map('current', $users); 

However, you should not rely on this. :)

+2
Nov 03 '11 at 12:10
source share



All Articles