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

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

    Similar to fuentesjrs solution, but a bit more generic using array_walk() with a custom callback:

    // Define the callback
    function extract_named_sub_elements(&$item, $key, $name) {
      $item = $item[$name];
    }
    
    // Test data
    $original = array(
      array('page' => 'page1', 'name' => 'pagename1'),
      array('page' => 'page2', 'name' => 'pagename2'),
      array('page' => 'page3', 'name' => 'pagename3'),
    );
    
    // Use a copy, as array_walk() operates directly on the passed in array
    $copy = $original;
    
    // Substitute 'name' with whatever element you want to extract, e.g. 'page'
    array_walk($copy, 'extract_named_sub_elements', 'name');
    
    print_r($copy);
    

提交回复
热议问题