ifaour ifaour - 7 months ago 20
PHP Question

How to get an array of specific "key" in multidimensional array without looping

Just like my previous question, this question is about learning something new in PHP.

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.

Answer

Since php 5.5, you can use array_column:

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

Since php 5.3, you can use array_map with an anonymous function, like this:

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

Before(Technically php 4.0.6+), you must create an anonymous function with create_function instead:

$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);