我在不同的目录中运行这个搜索文件名的脚本,它的问题不显示返回值,只有在使用打印或回显内部函数时才能工作,我认为这个问题是递归函数的返回值。
我的代码:
function search_file_dir($ruta, $search)
{
$dir = opendir("" . $ruta . "");
while ($file = readdir($dir)) {
if ($file != "." && $file != "..") {
if (is_dir("" . $ruta . "/" . $file . "")) {
$dir_out = "" . $file . "";
search_file_dir("" . $ruta . "/" . $file . "", "" . $search . "");
}
if (is_file("" . $ruta . "/" . $file . "")) {
if (substr($file, 0, -4) == $search) {
$ruta_end = "" . $ruta . "/" . $file . "";
}
}
}
}
closedir($dir);
return $ruta_end;
},并工作调用此
echo search_file_dir("gallery","flower.png")这是我的问题,因为在本例中,如何使用返回值来显示值,如果函数是递归的,函数可以很好地工作,并在所有类型的目录中搜索所有,但不工作返回。
以最高级的方式向表示感谢
发布于 2021-05-29 08:31:26
您不会返回每个递归的搜索结果。
当您的$ruta_end条件为真时,该函数返回is_file()。
但是当它是is_dir()时,会出现一个空响应,因为$ruta_end没有被分配一个值。这使得函数为根目录提供了一个有效的响应(正如您所提到的),但是当在子目录中搜索时,响应将为空。
基本上做这个$ruta_end = search_file_dir(...)
function search_file_dir($ruta, $search)
{
$dir = opendir("" . $ruta . "");
while ($file = readdir($dir)) {
if ($file != "." && $file != "..") {
if (is_dir("" . $ruta . "/" . $file . "")) {
$dir_out = "" . $file . "";
$ruta_end = search_file_dir("" . $ruta . "/" . $file . "", "" . $search . "");
}
if (is_file("" . $ruta . "/" . $file . "")) {
## Why are you using a substr -> to remove extension?
## If yes then it will not work on extensions like 'docx` (length more than 3)
## Use pathinfo() instead
## In your question the search term is flower.png so why remove extension in the first place. But I assume that is a typo
if (substr($file, 0, -4) == $search) {
$ruta_end = "" . $ruta . "/" . $file . "";
}
}
}
}
closedir($dir);
return $ruta_end;
}https://stackoverflow.com/questions/67748611
复制相似问题