How to Extract a 'Column' from an Array in PHP
In PHP, extracting specific values from multidimensional arrays can be a common task. Consider the following scenario where you have an array of arrays, as shown below:
array(array('page' => 'page1', 'name' => 'pagename1'), array('page' => 'page2', 'name' => 'pagename2'), array('page' => 'page3', 'name' => 'pagename3'))
You might want to extract the values of the 'name' key from each sub-array, giving you the following result:
array('pagename1', 'pagename2', 'pagename3')
array_column() Function (PHP 5.5 )
Introducing the powerful array_column() function, which simplifies this task significantly. For PHP versions 5.5 and above, array_column() is your go-to solution:
$samples = array( array('page' => 'page1', 'name' => 'pagename1'), array('page' => 'page2', 'name' => 'pagename2'), array('page' => 'page3', 'name' => 'pagename3') ); $names = array_column($samples, 'name'); print_r($names);
The above code will produce the desired result of ['pagename1', 'pagename2', 'pagename3'].
The above is the detailed content of How to Efficiently Extract a Specific Column from a Multidimensional Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!