Reputation: 846
I have an array which looks something like this:
$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' => []
]
]
],
];
I need a way to extract parts of it by key no matter where they are in the tree. I've tried several ways but I'm not sure how efficient they are. If it helps I need to extract only those parts which have a numeric key. Any help will be much appreciated.
Upvotes: 3
Views: 209
Reputation: 20753
Try using the 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);
}
Upvotes: 3