使用定界符在 PHP 中创建 JSON 树视图

Create a JSON tree view in PHP using delimiter

我正在尝试创建一个文件资源管理器类型的树视图 JSON 以供 FancyTree 读取我正在尝试的项目。

文件存储在数据库中,带有 ID、名称、URL、类型和代码字段。模拟数据库如下所示:

ID      name        URL.        Type            code
1       test        dir.dir1    txt             sometext
2       next        dir.dir1    txt             somemoretext
3       main        dir         txt            evenmoretext

我需要根据这些数据构建 JSON 树视图,使用 URL 作为路径(句点是分隔符)并且文件位于最终目录中,因此树看起来像

/dir/dir1/test.txt
/dir/dir1/next.txt
/dir/main.txt

FancyTree JSON 输出应该类似于

[
    {
        "title": "dir",
        "folder": true,
        "children": [
            {
                "title": "dir1",
                "folder": true,
                "children": [
                    {
                        "title": "test.txt",
                        "key": 1
                    }, {
                        "title": "next.txt",
                        "key": 2
                    }
                ]
            }, {
                "title": "main.txt",
                "key": 3
            }
        ]
    }
]

目前,我正在从数据库中获取数据到 $scriptArray

SELECT 'name','url','type','id' FROM.....

然后我用

排序并构建一棵树
    $url = array_column($scriptArray, 'url');
    array_multisort($url, SORT_ASC, $scriptArray);

    $result = [];

    foreach($scriptArray as $item) {
        $loop = 0;
        $keys = array_reverse(explode('.', $item->url));
        $tmp = $item->name;
        $tmp2 = $item->type;

        foreach ($keys as $keyid => $key) {
            if($loop == 0) {
                $tmp = ["title" => $tmp.".".$tmp2, 'key' => $item->id];
            } else {
                $tmp = ["title" => $keys[$keyid - 1], "folder" => true, "children" => [$tmp]];
            }
            $loop++;
        }
        $tmp = ["title" => $keys[count($keys)-1], "folder" => true, "children" => [$tmp]];

        $result[] = $tmp;
    }

但是,我得到的输出是。

[
    {
        "title": "dir",
        "folder": true,
        "children": [
            {
                "title": "dir2",
                "folder": true,
                "children": [
                    {
                        "title": "test.txt",
                        "key": 1
                    }
                ]
            }
        ]
    },
    {
        "title": "dir",
        "folder": true,
        "children": [
            {
                "title": "dir2",
                "folder": true,
                "children": [
                    {
                        "title": "next.txt",
                        "key": 2
                    }
                ]
            }
        ]
    },
    {
        "title": "main.txt",
        "key": 3
    }
]

我曾尝试应用 array_merge、array_merge_recursive 和其他各种方法,但均未成功。有人可以帮忙吗?

除非您事先知道文件夹层次结构的最大深度,否则无法使用循环。

更好的解决方案是“递归”构建文件夹路径,并将文件附加到最终文件夹。

这可以通过使用 & 运算符创建引用来实现,并导航到其子项直到构建整个路径:

$result = array();
foreach($files as $file)
{
    // build the directory path if needed
    $directories = explode('.', $file->url); // get hierarchy of directories
    $currentRoot = &$result ; // set the pointer to the root directory per default
    foreach($directories as $directory)
    {
        // check if directory already exists in the hierarchy
        $dir = null ;
        foreach($currentRoot as $i => $d)
        {
            if(isset($d['folder']) && $d['folder'] and $d['title'] == $directory)
            {
                $dir = &$currentRoot[$i] ;
                break ;
            }
        }
        
        // create directory if missing
        if(is_null($dir))
        {
            $item =  array(
                'title' => $directory,
                'folder' => true,
                'children' => array()
            );
            $currentRoot[] = $item ;
            $dir = &$currentRoot[count($currentRoot)-1];
        }
        
        // move to the next level
        $currentRoot = &$dir['children'] ; 
        unset($dir);
    }
    
    // finally append the file in the latest directory
    $currentRoot[] = array(
        'title' => $file->name . '.' . $file->type,
        'key' => $file->id,
    );
    
    
    unset($currentRoot);
}

echo json_encode($result);