This might be tangential to your question about the array, but you could kill two birds with one stone by using a recursive directory iterator.
$path_to_root = __DIR__;
$directories = new ParentIterator(new RecursiveDirectoryIterator($path_to_root, RecursiveDirectoryIterator::CURRENT_AS_SELF));
$iterator = new RecursiveIteratorIterator($directories, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $item)
{
printf("%d %s\n", $iterator->getDepth() + 1, $item->getSubPathname());
}
Which would output something like:
1 Root
2 Root/A
3 Root/A/A2
3 Root/A/A3
3 Root/A/A4
4 Root/A/A4/A4a
2 Root/B
3 Root/B/B2
3 Root/B/B3
2 Root/C
2 Root/D
2 Root/E
3 Root/E/E2
4 Root/E/E2/E2a
3 Root/E/E3
As you can see RecursiveIteratorIterator::getDepth()
is used to get the current depth of the recursive iterator, which is the reason for suggesting this approach.
Alternative (if you must use an array)
Assuming your array structure looks something like:
$dirs = array(
'Root' => array(
'A' => array(
'A2' => array(),
'A3' => array(),
'A4' => array(
'A4a' => array(),
),
),
'B' => array(
'B2' => array(),
'B3' => array(),
),
'C' => array(),
'D' => array(),
'E' => array(
'E2' => array(
'E2a' => array(),
),
'E3' => array(),
),
),
);
Then a very similar approach to getting the values from a recursive directory iterator (but this time with a recursive array iterator) can be used. A quick loop over the "parent" arrays can give us the "path" from the current item back to the root.
$recursive = new ParentIterator(new RecursiveArrayiterator($dirs));
$iterator = new RecursiveIteratorIterator($recursive, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $item)
{
// Build path from "parent" array keys
for ($path = "", $i = 0; $i <= $iterator->getDepth(); $i++) {
$path .= "/" . $iterator->getSubIterator($i)->key();
}
// Output depth and "path"
printf("%d %s\n", $iterator->getDepth() + 1, ltrim($path, "/"));
}
The output would be the same as the earlier one for the directory iterator.
TL;DR We can use recursive iterators from the SPL iterators to make working with recursive/deep structures much simpler.
TL;DR;TL;DR SPL, heck yeah!