我正在尝试获取格式如下的目录的多维数组:
[
{
"text": "another_folder",
"href": "gui\/default\/uploads\/another_folder",
"depth": 0
},
{
"text": "subfold",
"href": "gui\/default\/uploads\/subfold",
"depth": 0,
"nodes": {
"text": "sub-subfold",
"href": "gui\/default\/uploads\/subfold\/sub-subfold",
"depth": 1,
}
}
]
我想使用RecursiveIterators。到目前为止我所做的是我在给定路径中列出所有目录。我需要进入我堆积的儿童。
public function list_folders($folder_path='') {
if(!$folder_path) $folder_path = $this->upl_path;
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($folder_path),
RecursiveIteratorIterator::SELF_FIRST);
$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$r = array();
$counter = 0
foreach ($iterator as $splFileInfo) {
if($splFileInfo->isDir()) {
$r[$counter] = array(
'text' => $splFileInfo->getFilename(),
'href' => str_replace('\\','/',$splFileInfo->getPathname())
);
if(How to check if it has children) {
$result[$counter] += array('nodes'=> CALL RECURSIVE HERE ? );
}
$counter++;
}
echo json_encode($r,JSON_PRETTY_PRINT);
}
我很乐意使用任何想法或帮助。
答案 0 :(得分:3)
您的代码几乎可以正常运行,但缺少一些关键点。我调整了你的代码,使其有效,并添加了一些评论,希望能帮助你理解你所缺少的内容:
class FolderListing
{
public function list_folders($folder_path = '', $depth = 0)
{
if (!$folder_path) $folder_path = $this->upl_path;
$iterator = new IteratorIterator(new DirectoryIterator($folder_path));
$r = array();
foreach ($iterator as $splFileInfo) {
if ($splFileInfo->isDot()) {
continue;
}
// we need to do this for both folders and files
$info = array(
'text' => $splFileInfo->getFilename(),
'href' => str_replace('\\', '/', $splFileInfo->getPathname()),
'depth' => $depth
);
// is we have a directory, try and get its children
if ($splFileInfo->isDir()) {
// !!! I recommend to do an echo $splFileInfo->getPathname() here
// to see the order in which recursion works !!!
$nodes = $this->list_folders($splFileInfo->getPathname(), $depth + 1);
// only add the nodes if we have some
if (!empty($nodes)) {
$info['nodes'] = $nodes;
}
}
// add the info to the array. No need for a counter :)
$r[] = $info;
}
// the return is important to be able to build the multi dimensional array
return $r;
}
}
$test = new FolderListing();
$ret = $test->list_folders('./test'); // change this to whatever you want
var_dump($ret);
祝你好运!