This article is mainly to share with you the method that PHP gets the specified column in the array, for a multidimensional array (taking a two-dimensional array as an example), often need to get to one of the columns, such as a few user data, is a two-dimensional array, now need to obtain the names of these users, there are many ways to implement:
$arr = array (' id ' = ' = ' 101 ', ' name ' = = ' qu ', ' age ' =>28), array (' id ' = ' 102 ', ' name ' = ' " Array (' id ' = ' = ' 103 ', ' name ' = ' = ' zheng ', ' age ' =>22), array (' id ' = ' 104 ', ' name ' = = ' Zhu ', ' age ' =>23)) ;
Method One: use PHP built-in function array_column () to implement
Array Array_column (array $input, mixed $column _key [, Mixed $index _key])
Execute statement:
$result = Array_column ($arr, ' name '); Print_r ($result);
The results are as follows:
Array ( [0] = Qu [1] = you [2] = Zheng [3] = = Zhu)
If an optional parameter index_key is specified, the value of this column in the input array will be the key that returns the corresponding value in the array.
$result = Array_column ($arr, ' name ', ' id ');p rint_r ($result);
The results are as follows:
Array ( [101] = Qu [102] = [ 103] = Zheng [104] = Zhu)
This function should be used with caution, because the secondary function is only valid in versions above PHP5.5.
Method two: using PHP built-in function array_map () implementation
Array Array_map (callable $callback, array $arr 1 [, Array $ ...]
Array_map () returns an array that contains all the cells in the ARR1 after the callback action. The first parameter is a callback function, and the return value is an array in which each element of the array (ARR1) is processed by a callback function (callback).
Declare a handler function first:
function Get_val ($arr) {return $arr [' name '];}
Then act on the Array_map () function:
$result = Array_map (' Get_val ', $arr);p Rint_r ($result);
The results of the implementation are as follows:
Array ( [0] = Qu [1] = you [2] = Zheng [3] = = Zhu)
Here the first parameter of Array_map () is a callback function, and is a well-defined known function, here we can also use the anonymous function like JS:
$result = Array_map (function ($v) {return $v [' name '];}, $arr);
The result of the execution is the same.