PHP 实现遍历出目录及其子文件
手册(有PHP4的实现方式哦):
https://www.php.net/manual/zh/function.scandir.php
直接附代码吧
PHP5和PHP7 直接有scandir()函数,遍历出当前目录下的所有文件。
function myScanDir($dir) { $file_arr = scandir($dir); $new_arr = []; foreach($file_arr as $item){ if($item!=".." && $item !="."){ if(is_dir($dir."/".$item)){ $new_arr[$item] = myScanDir($dir."/".$item); }else{ $new_arr[] = $item; } } } return $new_arr; } $dir = myScanDir("aa"); var_dump($dir);
PHP4,通过opendir()、readdir()、closedir()配合实现:
function myScanDir($dir) { $dh = opendir($dir); $tmp_arr = []; while (false !== ($filename = readdir($dh))) { if($filename !=".." && $filename !="."){ if(is_dir($dir."/".$filename)){ $tmp_arr[$filename] = myScanDir($dir."/".$filename); }else{ $tmp_arr[] = $filename; } } } closedir($dh); return $tmp_arr; } $dir = myScanDir("aa"); var_dump($dir);
运行结果:
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23