
♻️主要归功于 递归 - Recursion
,又译为递回,在数学与计算机科学中,是指在函数的定义中使用函数自身的方法。递归一词还较常用于描述以自相似方法重复事物的过程。例如,当两面镜子相互之间近似平行时,镜中嵌套的图像是以无限递归的形式出现的。也可以理解为自我复制的过程(摘自维基百科)。
使用 dir 函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <?php
function dir_list($directory) { static $array = [];
$dir = dir($directory); while ($file = $dir->read()) { if (is_dir("$directory/$file") && $file !== '.' && $file !== '..') { dir_list("$directory/$file"); } else { if ($file !== '.' && $file !== '..') { $array[] = $file; } } }
return $array; }
|
使用 readdir 函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <?php
function dir_list(string $directory): array { static $array = [];
if ($dir = opendir($directory)) { while (false !== $file = readdir($dir)) { if (is_dir("$directory/$file") && $file !== '.' && $file !== '..') { dir_list("$directory/$file"); } else { if ($file !== '.' && $file !== '..') { $array[] = $file; } } } closedir($dir); }
return $array; }
|
使用 scandir 函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <?php
function dir_list(string $directory): array { static $array = [];
$dir = scandir($directory); foreach ($dir as $file) { if (is_dir("$directory/$file") && $file !== '.' && $file !== '..') { dir_list("$directory/$file"); } else { if ($file !== '.' && $file !== '..') { $array[] = $file; } } }
return $array; }
|
使用 RecursiveIteratorIterator 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <?php
function dir_list(string $directory): array { static $array = [];
$iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($iterator as $object) { $array[] = $object->getFileName(); }
return $array; }
|
函数调用:
1 2 3
| <?php
print_r(dir_list(dirname($_SERVER['PHP_SELF'])));
|
输出结果:
1 2 3 4 5 6 7 8 9 10 11 12 13
| Array ( [0] => myshell.sh [1] => meeting.md [2] => untitled.html [3] => server.php [4] => .DS_Store [5] => index.php [6] => desc.md . . . )
|