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

前端 未结 14 1409
鱼传尺愫
鱼传尺愫 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:

     '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'];
    

提交回复
热议问题