search

Home  >  Q&A  >  body text

Is there a way to retrieve specific "columns" from a PHP array?

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粉423694341P粉423694341398 days ago709

reply all(2)I'll reply

  • P粉514001887

    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);

    View actual operation

    reply
    0
  • P粉042455250

    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;
    }

    reply
    0
  • Cancelreply