使用PHP 函數遞歸遍歷目錄
如果您需要遍歷目錄及其子目錄,尋找包含的每個檔案和資料夾在其中,您可以建立一個遞歸PHP 函數來處理該任務。具體方法如下:
遞歸函數實作
function getDirContents($dir, &$results = array()) { $files = scandir($dir); foreach ($files as $key => $value) { $path = realpath($dir . DIRECTORY_SEPARATOR . $value); if (!is_dir($path)) { $results[] = $path; } else if ($value != "." && $value != "..") { getDirContents($path, $results); $results[] = $path; } } return $results; }
用法
像這樣呼叫函數:
用法$results = getDirContents('/xampp/htdocs/WORK'); var_dump($results);
像這樣呼叫函數:
array (size=12) 0 => string '/xampp/htdocs/WORK/iframe.html' (length=30) 1 => string '/xampp/htdocs/WORK/index.html' (length=29) 2 => string '/xampp/htdocs/WORK/js' (length=21) 3 => string '/xampp/htdocs/WORK/js/btwn.js' (length=29) 4 => string '/xampp/htdocs/WORK/js/qunit' (length=27) 5 => string '/xampp/htdocs/WORK/js/qunit/qunit.css' (length=37) 6 => string '/xampp/htdocs/WORK/js/qunit/qunit.js' (length=36) 7 => string '/xampp/htdocs/WORK/js/unit-test.js' (length=34) 8 => string '/xampp/htdocs/WORK/xxxxx.js' (length=30) 9 => string '/xampp/htdocs/WORK/plane.png' (length=28) 10 => string '/xampp/htdocs/WORK/qunit.html' (length=29) 11 => string '/xampp/htdocs/WORK/styles.less' (length=30)
以上是如何使用 PHP 遞歸遍歷目錄並取得所有檔案和資料夾路徑?的詳細內容。更多資訊請關注PHP中文網其他相關文章!