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

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

    You can extend the ArrayIterator class and override the method mixed current(void).

    class Foo extends ArrayIterator {
      protected $index;
      public function __construct($array, $index) {
        parent::__construct($array);
        $this->index = $index;
      }
    
      public function current() {
        $c = parent::current();
        return isset($c[$this->index]) ? $c[$this->index] : null;
      }
    }
    
    $a = array(
      array('page' => 'page1', 'name' => 'pagename1'),
      array('name' => '---'),
      array('page' => 'page2', 'name' => 'pagename2'),
      array('page' => 'page3', 'name' => 'pagename3')
    );
    
    $f = new Foo($a, 'page');
    foreach($f as $e) {
      echo $e, "\n";
    }
    

    prints

    page1
    
    page2
    page3
    

提交回复
热议问题