简体   繁体   English

用于打印文件和目录的PHP递归功能不起作用

[英]PHP recursive function for printing files and directories is not working

I am trying to make recursive PHP function which will loop through tree of directories and subdirectories and put all directories and files in one array. 我正在尝试制作递归PHP函数,该函数将遍历目录树和子目录树并将所有目录和文件放入一个数组中。

My code looks logical to me, but it is not working. 我的代码对我来说看起来很合逻辑,但无法正常工作。

Tree of directories and files: 目录和文件树:

在此处输入图片说明

PHP code PHP代码

    <?php
        function printFiles($directory) {
            $files = array();

            foreach (scandir($directory) as $file) {
                if ($file === '.' || $file === '..') 
                    continue;

                // checking is it file or directory
                if (is_dir($directory . '\\'. $file)) {
                    return printFiles($directory . '\\'.  $file);
                }

                array_push($files, $file);
            }

            return($files);
        }

        $directory = 'C:\Users\Jakov\Desktop\DIRECTORIES';
        print_r(printFiles($directory));

    ?>

I am getting this result: 我得到这个结果:

Array ( )

You are only getting the files contained in the first deepest folder your function encounters, A_1_1 , which has no files inside. 您只会得到函数遇到的第一个最深的文件夹A_1_1包含的文件,该文件夹中没有文件。

Don't return when you find a directory. 找到目录时不返回。 Add to current list instead: 改为添加到当前列表:

// checking is it file or directory
if (is_dir($directory . '/'. $file)) {
    $files = array_merge($files, printFiles($directory . '/'.  $file));
} else {
    array_push($files, $file);
}

Also, use / for paths. 另外,将/用作路径。 It works in Windows and you will avoid escaping errors: 它可以在Windows中使用,并且可以避免转义错误:

$directory = 'C:/Users/Jakov/Desktop/DIRECTORIES';

(In your code, you should be using \\\\ instead of \\ as separator.) (在代码中,应使用\\\\而不是\\作为分隔符。)

You should also check for links -and ignore them-, or you could get trapped in an infinite loop. 您还应该检查链接 -并忽略它们-否则您可能会陷入无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM