3

我有一个看起来像这样的数组:

$a = [
    1 => [
        'title' => 'test',
        'items' => [
            5 => [
                'title' => 'hello',
                'items' => []
            ]
        ]
    ],
    2 => [
        'title' => 'second',
        'items' => [
            7 => [
                'title' => 'hello in second',
                'items' => []
            ]
        ]
    ],
    3 => [
        'title' => 'third',
        'items' => [
            10 => [
                'title' => 'hello in third',
                'items' => []
            ]
        ]
    ],
];

我需要一种方法来通过密钥提取其中的一部分,无论它们在树中的什么位置。我尝试了几种方法,但我不确定它们的效率如何。如果有帮助,我只需要提取那些有数字键的部分。任何帮助都感激不尽。

4

1 回答 1

3

尝试使用SPL 迭代器:

class KeyFinderFilterIterator extends FilterIterator {
    private $search = null;
    public function __construct($iterator, $search) {
        $this->search = $search;
        parent::__construct($iterator);
    }
    public function accept(){
        return $this->key() == $this->search;
    }
}

 $it = new KeyFinderFilterIterator(
      new RecursiveIteratorIterator(
           new RecursiveArrayIterator($a), 
           RecursiveIteratorIterator::SELF_FIRST
      ), 
      10
 );

foreach ($it as $key => $value) {
    var_dump($value);
}
于 2012-11-22T20:50:22.417 回答