Is there a function to extract a 'column' from an array in PHP?

前端 未结 14 1406
鱼传尺愫
鱼传尺愫 2020-11-21 07:33

I have an array of arrays, with the following structure :

array(array(\'page\' => \'page1\', \'name\' => \'pagename1\')
      array(\'page\' => \'pa         


        
相关标签:
14条回答
  • 2020-11-21 08:13

    Not a 'built-in', but short arrow functions make for abrreviated explicit coding (introduced in Php v7.4.) and can be used with array_map for array transformations.

    Here applying a callback to each member of the array that returns the desired attribute from each subarray:

    <?php
    $data =
    [
        ['page' => 'page1', 'name' => 'pagename1'],
        ['page' => 'page2', 'name' => 'pagename2'],
        ['page' => 'page3', 'name' => 'pagename3']
    ];
    
    $names = array_map(fn($v) => $v['name'], $data);
    var_export($names);
    

    Output:

    array (
        0 => 'pagename1',
        1 => 'pagename2',
        2 => 'pagename3',
      )
    

    The OP posted this question before array_column exisited (from Php 5.5.0). This answers the original question with a short solution:

    $names = array_column($data, 'name');
    

    But a simple loop is also trite:

    foreach($data as $item) $names[] = $item['name'];
    
    0 讨论(0)
  • 2020-11-21 08:16

    Why does it have to be a built in function? No, there is none, write your own.

    Here is a nice and easy one, as opposed to others in this thread.

    $namearray = array();
    
    foreach ($array as $item) {
        $namearray[] = $item['name'];
    }
    
    0 讨论(0)
提交回复
热议问题