I have an array as follows:
$arr1 = array(
0 => array(
\'name\' => \'tom\',
\'age\' => 22
),
1 => array(
\'name\' => \'nick\',
if you are using Laravel, then simply use array_pluck
:
$arr2 = array_pluck($arr1 , 'name');
$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 )
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.
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