PHP仅打印返回数组的最后一个元素


PHP only printing last element of returned array

我正试图用一个递归函数来填充一个数组,该函数只使用以"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新手。

提前感谢!

当递归到子目录中时,需要将其结果合并到数组中。否则,数组只包含原始目录中的匹配文件,子目录中的匹配子将被丢弃。

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)){
                $array = array_merge($array, listFolderFiles($dir.'/'.$ff));
            }
        }
    }
    // At this point if I insert a foreach loop, 
    //   all of the elements will display properly
    return $array;
}

你需要更多地研究递归,你没有将$数组传递到递归调用中,所以你实际上只得到了第一个,所有后续调用的结果都会丢失

if(is_dir($dir.'/'.$ff)){
    listFolderFiles($dir.'/'.$ff);
}

对listFolderFiles的调用需要将这些文件添加到当前的$array中,并且该$array需要传递到后续调用中。阅读有关递归的更多信息。。

当打印行处于活动状态时,它在每次递归调用中都会被调用,而不是在末尾。