CKTIS / PHP
RecursiveIteratorIterator
Walk a RecursiveIterator tree without writing a recursive loop.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
new RecursiveIteratorIterator($recursive, RecursiveIteratorIterator::LEAVES_ONLY)Walk a RecursiveIterator tree without writing a recursive loop. LEAVES_ONLY emits leaf values, SELF_FIRST emits a parent before its descendants and CHILD_FIRST reverses that local order. Keys belong to each local level and can repeat in separate branches.
$tree=new RecursiveArrayIterator(["a"=>["id"=>1],"b"=>["id"=>2]]);
$walk=new RecursiveIteratorIterator($tree); $rows=[];
foreach($walk as $k=>$v){$rows[]=[$walk->getDepth(),$k,$v];} echo json_encode($rows);
[[1,"id",1],[1,"id",2]]
Examples
<?php
$tree=new RecursiveArrayIterator(["a"=>["id"=>1],"b"=>["id"=>2]]);
$walk=new RecursiveIteratorIterator($tree); $rows=[];
foreach($walk as $k=>$v){$rows[]=[$walk->getDepth(),$k,$v];} echo json_encode($rows);
Result
[[1,"id",1],[1,"id",2]]