php - PHP - 创建一个包含多个数组的 JSON 对象
问题描述
我有一个 PHP 函数来创建一个目录树,但我无法格式化结果以获得这样的 JSON 文件:
[
{
text: 'Parent',
href: 'parent/',
nodes: [
{
text: 'Child',
href: 'child/',
nodes: [
{
text: 'Grandchild',
href: 'grandchild/',
},
{
text: 'Grandchild',
href: 'grandchild/',
}
]
},
{
text: 'Child',
href: 'child/',
}
]
},
{
text: 'Parent',
href: 'parent/',
},
{
text: 'Parent',
href: 'parent/',
},
{
text: 'Parent',
href: 'parent/',
},
{
text: 'Parent',
href: 'parent/',
},
{
text: 'Parent',
href: 'parent/',
nodes: [
{
text: 'Child',
href: 'child/',
nodes: [
{
text: 'Grandchild',
href: 'grandchild/',
},
{
text: 'Grandchild',
href: 'grandchild/',
}
]
},
{
text: 'Child',
href: 'child/',
}
]
}
]
这是我的PHP函数,有人可以帮助我吗?谢谢
function scandir_rec($root)
{
$data = [];
if (!is_dir($root)) {
return;
}
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue;
}
$path = $root . '/' . $dir;
$data[] = ['text'=>$dir, 'link'=>urlencode($path)];
if (is_dir($path)) {
$data[] = ['nodes' => scandir_rec($path)];
}
}
return json_encode($data, JSON_UNESCAPED_SLASHES);
}
// init call
$rootDir = '/var/usr';
scandir_rec($rootDir);
解决方案
^那些人说的。
<?php
function scandir_rec($root)
{
$data = [];
if (!is_dir($root)) {
return;
}
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue;
}
$path = $root . DIRECTORY_SEPARATOR . $dir;
if (!is_dir($path)) continue;
$chunk = ['text' => $dir, 'link' => urlencode($path)];
$nodes = scandir_rec($path);
if (!empty($nodes)) $chunk['nodes'] = $nodes;
$data[] = $chunk;
}
return $data;
}
$rootDir = '/var/usr';
json_encode(scandir_rec($rootDir), JSON_UNESCAPED_SLASHES);
推荐阅读
- postgresql - activerecord 对多条记录的唯一约束
- python - 如何配对两个数据框
- python - 如何从某个列中获取大于另一列值的值?
- matlab - 使用 Matlab 绘制复指数函数
- laravel - 为什么我总是在新创建时清除路由和缓存路由?
- scapy - sendpfast 不起作用:如何包含 tcprelay
- javascript - 如何在javascript中一一播放多个mediaelementplayer
- javascript - 在Javascript中实现哈希表
- java - spring boot 返回 200,并将“OK”ErrorAttributes 附加到正常的身体响应
- reactjs - 如何告诉 nextjs 只捆绑我从字典文件中使用的单词