Home >Backend Development >PHP Tutorial >How Can I Extract a Specific Column from a Multidimensional Array in PHP?
Original Question: Is there a function to extract a 'column' from an array in PHP?
Scenario:
Consider an array of arrays structured as follows:
array( array('page' => 'page1', 'name' => 'pagename1'), array('page' => 'page2', 'name' => 'pagename2'), array('page' => 'page3', 'name' => 'pagename3') )
The goal is to obtain a new array that contains only the values of the 'name' keys:
array('pagename1', 'pagename2', 'pagename3')
Solution:
Since PHP 5.5
PHP 5.5 introduced the array_column() function, which is ideally suited for this task:
$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); // ['pagename1', 'pagename2', 'pagename3']
This code uses array_column() to extract the 'name' column from the $samples array, resulting in the desired output.
The above is the detailed content of How Can I Extract a Specific Column from a Multidimensional Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!