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 に答える