【发布时间】:2014-09-10 20:18:11
【问题描述】:
我正在尝试使用递归函数查看子目录列表来填充仅包含以“mp4”结尾的文件名的数组。
当我在返回语句之前使用 foreach 循环打印数组中的元素时,数组会正确显示所有元素。但是,当我从方法的返回创建一个变量并尝试再次遍历它时,我只收到数组中的最后一个条目。
这可能是循环中的递归造成的吗?
我的代码如下:
<?php
function listFolderFiles($dir){
$array = array();
$ffs = scandir($dir);
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
// This successfully adds to the array.
if(substr($ff, -3) == "mp4"){
$array[] = $ff;
}
// This steps to the next subdirectory.
if(is_dir($dir.'/'.$ff)){
listFolderFiles($dir.'/'.$ff);
}
}
}
// At this point if I insert a foreach loop,
// all of the elements will display properly
return $array;
}
// The new '$array' variable now only includes the
// last entry in the array in the function
$array = listFolderFiles("./ads/");
foreach($array as $item){
echo $item."<p>";
}
?>
任何帮助将不胜感激!我为草率道歉。我是 PHP 新手。
提前致谢!
【问题讨论】:
-
当你进行递归调用时,你不会对它的返回值做任何事情。
-
我敢打赌所有
.mp4文件都在子目录中,而不是顶级目录中。 -
它对我来说很好:)
-
@Barmar 我确保它会检查。
标签: php arrays foreach directory ads