我有一个最多包含10个级别的目录结构(可能有所不同),给定目录名,我想返回与给定目录名匹配的第一个目录的完整路径。
public function LocalDirSearch($clouse) {
$path = $clouse[0];
$search = $clouse[1];
$result = $clouse[2];
$dirs = glob($path, GLOB_ONLYDIR);
foreach ($dirs as $dir) {
if(basename($dir)==$search){
return $dir;
break;
}
$this->LocalDirSearch([$dir,$search,$result]);
}
}
我制作了这个脚本,但是无法正常运行,我不知道它到底缺少什么,并且可以无限期地运行...没有错误输出...
更新
此目录结构:
+--pdf
+---+---i-pdf-0034
+---+---+---form
+---+---+---+---data
+---+---+---+---other
+---+---i-pdf-0045
+---+---+---form
+---+---+---+---data
+---+---+---+---other
+---+---i-pdf-0056
+---+---+---form
+---+---+---+---data
+---+---+---+---other
+--doc
+---+---i-doc-0034
+---+---+---form
+---+---+---+---data
+---+---+---+---other
+---+---i-doc-0045
+---+---+---form
+---+---+---+---data
+---+---+---+---other
+---+---i-doc-0056
+---+---+---form
+---+---+---+---data
+---+---+---+---other
函数调用:
$this->LocalDirSearch(['C:/xampp/htdocs/files','i-pdf-0045']);
用于搜索目录的脚本:
public function LocalDirSearch($clouse) {
$path = $clouse[0];
$search = $clouse[1];
$dirs = glob($path . '/*', GLOB_ONLYDIR);
foreach ($dirs as $dir) {
if (basename($dir) == $search) {
return $dir;
}else{
// return the result of the recursive call
return $this->LocalDirSearch([$dir, $search]);
}
}
}
目录中递归打印导航的输出:
'C:/xampp/htdocs/files/'
'C:/xampp/htdocs/files/pdf/'
'C:/xampp/htdocs/files/pdf/i-pdf-0034/'
'C:/xampp/htdocs/files/pdf/i-pdf-0034/form/'
'C:/xampp/htdocs/files/pdf/i-pdf-0034/form/data/' #out of search
返回:
'NULL'
答案 0 :(得分:0)
两个主要问题:
这意味着它将永远找不到您的目标(除非您的目标恰好是您在其中启动的目录),因此它将永远不会返回。
尝试进行以下更改
public function LocalDirSearch($clouse) {
$path = $clouse[0];
$search = $clouse[1];
$result = $clouse[2];
// add a wildcard to the glob pattern so it will match everything under $path
$dirs = glob($path . '/*', GLOB_ONLYDIR);
foreach ($dirs as $dir) {
if (basename($dir)==$search){
return $dir;
}
// return the result of the recursive call
if ($subdir = $this->LocalDirSearch([$dir, $search, $result])) {
return $subdir;
}
}
}
偶然地,break
之后不需要return
,并且该功能中似乎没有使用$result
。