- scandir: documentation ( source)
- microtime: documentation ( source)
- array_merge_recursive: documentation ( source)
- is_dir: documentation ( source)
<?php
function dirToArray1($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value,array(".",".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
$result[$value] = dirToArray1($dir . DIRECTORY_SEPARATOR . $value);
} else {
$result[] = $value;
}
}
}
return $result;
}
function dirToArray2($dir) {
$arr = [];
$obj = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($obj as $info) {
if (in_array($info->getFilename(), ['.', '..'])) continue;
$path = $info->isDir() ? [$info->getFilename() => []] : [$info->getFilename()];
for ($depth = $obj->getDepth() - 1; $depth >= 0; $depth--) {
$path = [$obj->getSubIterator($depth)->current()->getFilename() => $path];
}
$arr = array_merge_recursive($arr, $path);
}
return $arr;
}
foreach (['2'] as $k) {
$t = "t$k";
$d = "d$k";
$$t = microtime(true);
$func = "dirToArray$k";
$$d = $func("/");
$$t = microtime(true) - $$t;
echo "$func needed " . $$t . " time\n";
}