If you have a large set of multidimensional array and you want to only get array of specific key for multidimensional array using PHP, After release of php 5.5+ These is predefined function called array_column. It Return the values from a single column in the input array. Like you have write a query to fetch data from database get multidimensional array result and you only want selected column field from array then this simple function reduce your effort and also helpful to optimize your code.
Sample multidimensional array:
$companyArr = array( array( 'id'=>1, 'name'=>'HCL', 'city'=>'Noida' ), array( 'id'=>1, 'name'=>'Infosys', 'city'=>'Bangalore' ), array( 'id'=>1, 'name'=>'Wipro', 'city'=>'Gurgaon' ) ); |
Now you want to retrieve all the city’s from $companyArr array and create an array of cities. The following single line of code will do it easily.
$cities = array_column($companyArr, 'city'); /* OUTPUT: Array ( [0] => Noida [1] => Bangalore [2] => Gurgaon ) */ |
Another example to get all the company names array only by array_column
$companyNames = array_column($companyArr, 'name'); /* OUTPUT: Array ( [0] => HCL [1] => Infosys [2] => Wipro ) */ |