$data = [ '1' => [ '2' => [ '3' => 'foo', '4' => 'bar', ], '5' => 'baz', ], ]; $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data)); foreach ($it as $key => $value) { echo "Depth: " . $it->getDepth() . ", Key: $key, Value: $value\n"; }
$data = [ '1' => [ '2' => [ '3' => 'foo', '4' => 'bar', ], '5' => 'baz', ], ]; $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data)); foreach ($it as $key => $value) { if ($it->getDepth() > 1) { // Skip elements deeper than level 1 continue; } echo "Key: $key, Value: $value\n"; }In this example, getDepth() is used to detect whether an element is deeper than level 1. If it is, the element is skipped and not printed. The RecursiveIteratorIterator class is a part of the standard PHP library, so no extra package library is required.