傳統方法:
在讀取某個文件夾下的內容的時候
使用 opendir readdir結合while循環過濾 當前文件夾和父文件夾來操作的
function readFolderFiles($path) { $list = []; $resource = opendir($path); while ($file = readdir($resource)) { //排除根目錄 if ($file != ".." && $file != ".") { if (is_dir($path . "/" . $file)) { //子文件夾,進行遞歸 $list[$file] = readFolderFiles($path . "/" . $file); } else { //根目錄下的文件 $list[] = $file; } } } closedir($resource); return $list ? $list : []; }
方法二
使用 scandir函數 可以掃描文件夾下內容 代替while循環讀取
function scandirFolder($path) { $list = []; $temp_list = scandir($path); foreach ($temp_list as $file) { //排除根目錄 if ($file != ".." && $file != ".") { if (is_dir($path . "/" . $file)) { //子文件夾,進行遞歸 $list[$file] = scandirFolder($path . "/" . $file); } else { //根目錄下的文件 $list[] = $file; } } } return $list; }