我试图获得多维数组的目录格式如下:
[
{
"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,
}
}
]
我想使用递归迭代器。到目前为止,我所做的是获得给定路径中列出的所有目录。我需要进入到children,也就是我堆叠的地方。
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);
}
我很乐意使用任何想法或帮助。 您的代码几乎是功能性的,但是它缺少几个关键点。我修改了你的代码,使其工作,并添加了一些注释,我希望能帮助你理解你错过了什么:
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);
祝你好运!