gpt4 book ai didi

php - 在 PHP 中搜索一个目录,从末尾开始

转载 作者:搜寻专家 更新时间:2023-10-31 21:07:44 24 4
gpt4 key购买 nike

<分区>

我有这段PHP代码,但我以前只写过一个递归函数。我想从一个特定的子目录开始并检查文件是否存在。如果它在目录中不存在,我想检查文件的父文件夹,然后递归地继续,直到我找不到文件并返回“”或找到文件并返回其内容。这是我的功能:

/**
* Recursive function to get sidebar from path and look up tree until we either
* find it or return blank.
*/
class MyClass{
public function findSidebarFromPath($path){
if(file_exists($_SERVER["DOCUMENT_ROOT"] . implode("/", $path) . "/sidebar.html")){
return file_get_contents($_SERVER["DOCUMENT_ROOT"] . implode("/", $path) . "/sidebar.html");
} else {
if(count($path) > 0){
# Pop element off end of array.
$discard = array_pop($path);
$this->findSidebarFromPath($path);
} else {
return "";
}
}
}
}

所以当我调用它时,我会这样做:

$myclass = new MyClass();
$myclass->findSidebarFromPath(array("segment1", "segment2", "segment3"));

假设我要查找的文件位于名为“segment2”的目录中。该函数永远找不到它。 array_pop 函数不会弹出数组末尾的元素,然后调用 findSidebarFromPath 函数。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com