I have an array of arrays with the following structure:
array(array('page' => 'page1', 'name' => 'pagename1') array('page' => 'page2', 'name' => 'pagename2') array('page' => 'page3', 'name' => 'pagename3'))
Is there a built-in function that returns a new array containing only the "name" key value? So I would get:
array('pagename1', 'pagename2', 'pagename3')
P粉5140018872023-10-21 17:49:30
Starting in PHP 5.5
you can use array_column()
:
<?php $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);
P粉0424552502023-10-21 11:46:32
Why does it have to be a built-in function? No, no, write it yourself.
This is a nice and simple approach compared to others in this thread.
$namearray = array(); foreach ($array as $item) { $namearray[] = $item['name']; }
In some cases, if the key is not named, you can do this
$namearray = array(); foreach ($array as $key => $value) { $namearray [] = $value; }