【发布时间】:2021-12-25 04:58:01
【问题描述】:
那里,
我尝试了很多次将递归函数的答案放入一个数组 ($result) 中,但我做不到。代码如下:
function readDirs($path , $result = [])
{
$dirHandle = opendir($path);
while($item = readdir($dirHandle))
{
$newPath = $path."/".$item;
if(is_dir($newPath) && $item != '.' && $item != '..')
{
readDirs($newPath, $result);
}
elseif(!is_dir($newPath) && $item != '.DS_Store' && $item != '.' && $item != '..')
{
echo "$path<br>";
$result[] = $path;
return $result;
}
}
}
$path = "/Users/mycomputer/Documents/www/Photos_projets";
$results = array();
readDirs($path, $results);
你能帮我把路径放在数组中吗,因为我稍后在我的代码中需要它们? 谢谢
【问题讨论】:
-
最明显的是你没有使用
readDirs()来分配变量。一个好的第一步是$result = readDirs($path);。 -
尝试通过将
readDirs($path , $result = [])更改为readDirs($path , &$result)将$results数组作为引用传递。那你就不需要退货了。外部$results将在函数调用后填充。
标签: php arrays function recursion