How can RecursiveIteratorIterator be used to create a nested array structure for directories and files in PHP?

RecursiveIteratorIterator can be used to iterate over directories and files in a nested structure. By using RecursiveDirectoryIterator to get a list of directories and files, and then using RecursiveIteratorIterator to iterate over them in a nested manner, we can create a nested array structure that represents the directories and files. This can be useful for tasks such as displaying a directory tree or processing files in a hierarchical manner.

<?php
$directory = 'path/to/directory';

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($directory),
    RecursiveIteratorIterator::SELF_FIRST
);

$nestedArray = [];

foreach ($iterator as $file) {
    $path = $iterator->getSubPathName();
    $pathArray = explode("/", $path);
    
    $currentArray = &$nestedArray;
    foreach ($pathArray as $key) {
        if (!isset($currentArray[$key])) {
            $currentArray[$key] = [];
        }
        $currentArray = &$currentArray[$key];
    }
}

print_r($nestedArray);
?>