我撰寫了一個函式來查找特定目錄及其子目錄中的檔案。您可以輸入帶或不帶擴展名的檔案名(basename vs. filename)。第二個引數是要搜索的路徑。檔案在給定目錄中時找到,但是,如果它在子目錄中,則找不到。我嘗試利用函式的 recursive 呼叫來查看子目錄。有什么我想念的想法嗎?
public function findFileInPathRecursive($file_to_find, $path) {
if (substr($path, -1) != "/") $path .= "/"; // Add slash at path's end
$files = scandir($path);
foreach($files as $file) {
if (substr($file, 0, 1) == ".") continue; // skip if "." or ".."
if (is_dir($path.$file)) { // if "file" is a directory, call self with the new path
$new_path = $path.$file;
return $this->findFileInPathRecursive($file_to_find, $new_path);
}
else {
if (pathinfo($file)['basename'] == $file_to_find OR pathinfo($file)['filename'] == $file_to_find) {
return $path.$file;
}
}
}
return false;
}
uj5u.com熱心網友回復:
我相信return $this->findFileInPathRecursive($file_to_find, $new_path);
當第一個子檔案夾不包含該檔案時,這將導致提前回傳。
您可以通過僅在找到檔案時回傳來避免。
if($found = $this->findFileInPathRecursive($file_to_find, $new_path)) {
return $found;
}
public function findFileInPathRecursive($file_to_find, $path) {
if (substr($path, -1) != "/") $path .= "/"; // Add slash at path's end
$files = scandir($path);
foreach($files as $file) {
if (substr($file, 0, 1) == ".") continue; // skip if "." or ".."
if (is_dir($path.$file)) { // if "file" is a directory, call self with the new path
$new_path = $path.$file;
// We only want to return file
if($found = $this->findFileInPathRecursive($file_to_find, $new_path)) {
return $found;
}
}
else {
if (pathinfo($file)['basename'] == $file_to_find OR pathinfo($file)['filename'] == $file_to_find) {
return $path.$file;
}
}
}
return false;
}
uj5u.com熱心網友回復:
* Search recusively for files in a base directory matching a glob pattern.
* The `GLOB_NOCHECK` flag has no effect.
* @param string $base Directory to search
* @param string $pattern Glob pattern to match files
* @param int $flags Glob flags from https://www.php.net/manual/function.glob.php
* @return string[] Array of files matching the pattern
function glob_recursive($base, $pattern, $flags = 0) {
$flags = $flags & ~GLOB_NOCHECK;
if (substr($base, -1) !== DIRECTORY_SEPARATOR) {
$base .= DIRECTORY_SEPARATOR;
}
$files = glob($base.$pattern, $flags);
if (!is_array($files)) {
$files = [];
}
$dirs = glob($base.'*', GLOB_ONLYDIR|GLOB_NOSORT|GLOB_MARK);
if (!is_array($dirs)) {
return $files;
}
foreach ($dirs as $dir) {
$dirFiles = glob_recursive($dir, $pattern, $flags);
$files = array_merge($files, $dirFiles);
}
return $files;
}
$files = glob($base.$pattern, $flags);
$files = $files !== false ? $files : [];
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/470047.html
下一篇:Soduko求解函式需要遞回