//php 遞歸實現遍歷 用dir 返回對象 <? function loop($dir){ $mydir =dir($dir); //以對象的形式訪問 while($file = $mydir ->read()){ //目錄中有隱藏文件'.'和'..' 遍歷的時候須要注意 if((is_dir("$dir/$file")) && ($file!=".") && ($file!="..")){ echo $file.'</br>'; loop("$dir/$file"); //遞歸循環 }else{ if($file!=".." && $file!="."){ echo $file."</br>"; } } } } loop(dirname(__FILE__)); //dirname 去掉文件名返回目錄名
非遞歸處理遍歷目錄php
思路: 首先建立一個數組,由於第一次傳的是一個去掉文件名的目錄名(如 c://wamp/www/php)數組
進行foreach 循環 因此第一次把C://wamp/www/php 下的所有文件都放入到了 數組中/只夠進行 while大循環 每次輸出數組的最後一個,當文件爲目錄的時候在此進行foreach循環ide
知道最後一個值時count($list)值爲0 退出循環oop
function scanAll($dir) { $list = array(); $list[] = $dir; while (count($list) > 0) { // var_dump($list); //彈出數組最後一個元素 $file = array_pop($list); //處理當前文件 echo $file."</br>"; //若是是目錄 if (is_dir($file)){ $children = scandir($file); var_dump($children); foreach ($children as $child){ if ($child !== '.' && $child !== '..'){ $list[] = $file.'/'.$child; } } } } } scanAll(dirname(__FILE__));
PHP SPL 實現 遍歷文件夾的文件spa
$path = dirname(__FILE__)."\\"; // 路徑 echo $path."</br>"; $directory = new RecursiveDirectoryIterator($path); //The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories. $recursive = new RecursiveIteratorIterator($directory,RecursiveIteratorIterator::SELF_FIRST); //各項都包含,例如遞歸文件夾就會連同子文件夾名稱也做爲其中項輸出,順序是先父後子 foreach($recursive as $file) { echo str_repeat("\t", $recursive->getDepth()); // 獲取當前的深度 if ($file->isDir()) { echo DIRECTORY_SEPARATOR; //DIRECTORY_SEPARATOR是php的內部常量,用於顯示系統分隔符的命令,不須要任何定義與包含便可直接使用 } echo $file->getBasename(); //Gets the base name of the file if ($file->isFile()) { echo "(" . $file->getSize() . "bytes)"; } else if ($file->isLink()) { //判斷是不是一個符號連接 echo "(symlink)"; } echo "</br>"; } //echo $path;