php - 如何使用 php 获取子文件夹的文件列表并将它们写入 JSON 中?

标签 php json

我已经能够列出所有文件名和当前目录/文件夹,但我不知道如何为子目录创建 JSON 条目

这是我的代码

<?php
$dir = "office/";
if(is_dir($dir)){
    if($dh = opendir($dir)){
        while(($file = readdir($dh)) != false){
            if($file != "." and $file != ".."){
                $files_array[] = array('file' => $file); // Add the file to the array
            } 
        }
    }
    $return_array =array('dir' => $files_array);
    exit (json_encode($return_array));
}
?>

输出为

{
    "dir": [
        {
            "file": "FreeWallpapersApp.zip"
        },
        {
            "file": "20151211_ClipArtForTextView.7z"
        },
        {
            "file": "QRite.7z"
        },
        {
            "file": "CustomDialog_app_contacts.zip"
        },
        {
            "file": "LockScreenBasicApp.apk"
        },
        {
            "file": "ImgViewEffects.zip"
        },
      ]
    }

如何使用 php 显示子文件夹内的文件并生成子目录中的文件名。

最佳答案

实现目录递归列表的一种方法是使用递归函数。

/*
 * Converts a filesystem tree to a PHP array.
 */
function dir_to_array($dir)
{
        if (! is_dir($dir)) {
                // If the user supplies a wrong path we inform him.
                return null;
        }

        // Our PHP representation of the filesystem
        // for the supplied directory and its descendant.
        $data = [];

        foreach (new DirectoryIterator($dir) as $f) {
                if ($f->isDot()) {
                        // Dot files like '.' and '..' must be skipped.
                        continue;
                }

                $path = $f->getPathname();
                $name = $f->getFilename();

                if ($f->isFile()) {
                        $data[] = [ 'file' => $name ];
                } else {
                        // Process the content of the directory.
                        $files = dir_to_array($path);

                        $data[] = [ 'dir'  => $files,
                                    'name' => $name ];
                        // A directory has a 'name' attribute
                        // to be able to retrieve its name.
                        // In case it is not needed, just delete it.
                }
        }

        // Sorts files and directories if they are not on your system.
        \usort($data, function($a, $b) {
                $aa = isset($a['file']) ? $a['file'] : $a['name'];
                $bb = isset($b['file']) ? $b['file'] : $b['name'];

                return \strcmp($aa, $bb);
        });

        return $data;
}

/*
 * Converts a filesystem tree to a JSON representation.
 */
function dir_to_json($dir)
{
        $data = dir_to_array($dir);
        $data = json_encode($data);

        return $data;
}

在您的示例中,

echo dir_to_json('office/');

会输出这个

{ 
    "dir": [
        {
            "file": "FreeWallpapersApp.zip"
        },
        {
            "file": "20151211_ClipArtForTextView.7z"
        },
        // ...
        {
            "dir": [
                {
                    "file": "App.zip"
                },
                {
                    "file": "View.7z"
                },
                "name": "A Directory With Files",
            ]
        },
    ]
}

更新 1:

我更新了答案以显式对文件和目录进行排序。

关于php - 如何使用 php 获取子文件夹的文件列表并将它们写入 JSON 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59540543/

相关文章:

javascript - JSON.parse 在 PhoneGap 中不起作用

php - 跨网页布局的多个 MySQL 查询 - 最好的方法是什么?

php - 如何确保处理 ajax 请求的 PHP 脚本不可访问且用户已通过身份验证?

javascript - 在play框架中从javascript调用java函数

python - 嵌套的 json 字段上的 Django order_by

php - 如何在数据库中存储作为 POST 传递的多个参数

java - 将 JSONObject 转换为 JSONArray 异常

php - 使用集成身份验证在 PHP 中连接到 MSSQL 服务器

php - 如何计算 CakePHP 3.x 中 page() 使用的 OFFSET 值?

php - 如何解决mySQL插入查询中的连字符问题