Answer the question
In order to leave comments, you need to log in
How to generate JSON directory with files getting recursive path?
It is necessary to generate a JSON form similar to this:
It turned out that I could do this type:
With this code:
<?php
function get_filelist_as_array($dir, $recursive = true, $basedir = '') {
if ($dir == '') {return array();} else {$results = array(); $subresults = array();}
if (!is_dir($dir)) {$dir = dirname($dir);}
if ($basedir == '') {$basedir = realpath($dir).DIRECTORY_SEPARATOR;}
$files = scandir($dir);
foreach ($files as $key => $value){
if ( ($value != '.') && ($value != '..') ) {
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if (is_dir($path)) {
if ($recursive) {
$subdirresults = get_filelist_as_array($path,$recursive,$basedir);
$results = array_merge($results,$subdirresults);
}
} else {$subresults[] = str_replace($basedir,'',$path); }
}
}
if (count($subresults) > 0) {
$results = array_merge($subresults,$results);
foreach ($results as $key => $res){
$time = time();
$size = filesize($res);
$hash = md5_file($res);
$a[] = array("type" => "file", "name" => "$res", "data_change" => "$time", "size" => "$size", "hash" => "$hash");
}
}
file_put_contents("update.json", json_encode(array('data'=>$a)));
return $results;
}
$dir = 'C:\Users\Администратор\Desktop\FILES;
return get_filelist_as_array($dir);
Answer the question
In order to leave comments, you need to log in
Something like this:
<?php
function tree($dirName) {
$tree = [];
$dir = opendir($dirName);
while (($entry = readdir($dir)) !== false) {
if ($entry === '.' || $entry === '..') {
continue;
}
$fullName = "{$dirName}\\{$entry}";
if (is_dir($fullName)) {
$tree[] = [
'name' => $entry,
'type' => 'dir',
'entries' => tree($fullName)
];
} else {
$tree[] = [
'name' => $entry,
'type' => 'file'
];
}
}
return $tree;
}
print(json_encode(tree('C:\\test'), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
/* [
{
"name": "dir1",
"type": "dir",
"entries": [
{
"name": "dir2",
"type": "dir",
"entries": [
{
"name": "file5",
"type": "file"
}
]
},
{
"name": "file1",
"type": "file"
},
{
"name": "file3",
"type": "file"
}
]
},
{
"name": "file2",
"type": "file"
}
] */
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question