$array = array( "a" => array( "b" => "c", "d" => array("e" => "f") ), "g" => "h" ); $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); foreach ($iterator as $key => $value) { $depth = $iterator->getDepth(); echo "Depth Level: {$depth} Key: {$key} Value: {$value} \n"; }
$directory = '/path/to/directory'; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)); foreach ($iterator as $file) { if ($file->isFile()) { echo "File: " . $file->getFileName() . " Path: " . $file->getPath() . "\n"; } }Both examples use the RecursiveIteratorIterator class to traverse through nested arrays and directories recursively. The second example uses it in conjunction with the RecursiveDirectoryIterator class. The SPL (Standard PHP Library) package library includes classes for data structures, iterators, and other useful tools to make programming easier.