我有问题根据以下结构将数组目录(文件夹和文件)转换为json转换:
我尝试在网上搜索但没有任何效果。 我为此任务编写的最后一个代码:
<?php
$path = 'data';
function get_Dir($path){
$dir = scandir($path);
$filesss = array();
$a = 0;
foreach($dir as $v){
if($v == '.' || $v == '..') continue;
if(!is_dir($path.'/'.$v)){
$files[] = 'name:'.basename($v).','.'size:3938';
}else{
$files['name'] = basename($path.'/'.$v);
//$change = basename($path.'/'.$v);
$files['children'.$a] = get_dir($path.'/'.$v);
}
$a++;
}
return $files;
}
?>
请帮忙。 谢谢。
答案 0 :(得分:0)
试试这个:
<?php
function getTree($path) {
$dir = scandir($path);
$items = array();
foreach($dir as $v) {
// Ignore the current directory and it's parent
if($v == '.' || $v == '..')
continue;
$item = array();
// If FILE
if(!is_dir($path.'/'.$v)) {
$fileName = basename($v);
$file = array();
$file['name'] = $fileName;
$file['size'] = '122';
$item = $file;
} else {
// If FOLDER, then go inside and repeat the loop
$folder = array();
$folder['name'] = basename($v);
$childs = getTree($path.'/'.$v);
$folder['children'] = $childs;
$item = $folder;
}
$items[] = $item;
}
return $items;
}
$path = 'data';
$tree['name'] = 'Main node';
$tree['children'] = getTree($path);
$json = json_encode($tree, JSON_PRETTY_PRINT);
echo '<pre>';
echo $json;
echo '</pre>';
?>