Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an array from the values of another array's key?

I have an array as follows:

$arr1 = array(
  0 => array(
    'name' => 'tom',
    'age' => 22
  ),
  1 => array(
    'name' => 'nick',
    'age' => 18
  )
);

However I want to create an array from it which consists of all the names, so it would become:

$arr2 = array('tom', 'nick');

I have looked at array_filter(), but that would not work as this is a multi-dimensional array!

Question

How can I create an array with the values of a specific key (name) from another multi-dimensional array?

like image 730
newbtophp Avatar asked Dec 29 '10 02:12

newbtophp


People also ask

How do you create an array of values?

You can make an array of int s, double s, or any other type, but all the values in an array must have the same type. To create an array, you have to declare a variable with an array type and then create the array itself. Array types look like other Java types, except they are followed by square brackets ( [] ).

How do you push a key into an array?

You can use the union operator ( + ) to combine arrays and keep the keys of the added array. For example: <? php $arr1 = array('foo' => 'bar'); $arr2 = array('baz' => 'bof'); $arr3 = $arr1 + $arr2; print_r($arr3); // prints: // array( // 'foo' => 'bar', // 'baz' => 'bof', // );


3 Answers

Newer versions of PHP allow using array_map() with a function expression instead of a function name:

$arr2 = array_map(function($person) {
    return $person['name'];
}, $arr1);

But if you are using a PHP < 5.3, it is much easier to use a simple loop, since array_map() would require to define a (probably global) function for this simple operation.

$arr2 = array();

foreach ($arr1 as $person) {
    $arr2[] = $person['name'];
}

// $arr2 now contains all names
like image 73
jwueller Avatar answered Oct 21 '22 04:10

jwueller


This can be done in still more simple way by using array_column

$arr2= array_column($arr1, 'name');

print_r($arr2); //Array ( [0] => tom [1] => nick )

array_column is used to get the columns of a sub-array.

like image 28
JVT Avatar answered Oct 21 '22 02:10

JVT


$array = array(0 => array('name' => 'tom', 'age' => 22), 1 => array('name' => 'nick', 'age' => 18));
foreach($array as $arr => $a){
    $names[] = $array[$arr]["name"];
}

print_r($names); //Array ( [0] => tom [1] => nick ) 
like image 3
Dejan Marjanović Avatar answered Oct 21 '22 04:10

Dejan Marjanović