提取多维数组的一部分的有效方法

时间:2012-11-22 20:28:16

标签: php

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

$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' => []
            ]
        ]
    ],
];

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

1 个答案:

答案 0 :(得分:3)

尝试使用SPL iterators:

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);
}