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!
How can I create an array with the values of a specific key (name
) from another multi-dimensional array?
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 ( [] ).
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', // );
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
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.
$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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With