我想构建一个 Json 输出来列出 ExtJS 树面板中的文件夹结构。该结构应该等同于 Json 中的这个数组:
Array
(
[text] => .
[children] => Array
(
[0] => Array
(
[text] => files
[children] =>
)
[1] => Array
(
[text] => folder 1
[children] =>
)
[2] => Array
(
[text] => New directory
[children] => array(
[0] => Array
(
[text] => sub_1
[children] => array(
[0] => Array
(
[text] => sub_1_1
[children] =>
)
[1] => Array
(
[text] => sub_1_2
[children] =>
)
)
)
[1] => Array
(
[text] => sub_2
[children] =>
)
)
)
)
)
我制作了这个函数,通过 PHP 手册和示例显示结构
listFolders('../file_uploads/');
function listFolders($dir){
$dh = scandir($dir);
echo '<ul>';
foreach($dh as $folder){
if($folder != '.' && $folder != '..')
{
if(is_dir($dir.'/'.$folder)){
echo '<li>'.$folder.'</li>';
listFolders($dir.'/'.$folder);
}
}
}
echo '</ul>';
}
这输出结构
- 新目录
- sub_1
- sub_1_1
- sub_1_1_1
- sub_1_2
- sub_2
- 文件
- 文件夹 1
我想知道如何将此输出转换为上面的数组(或 Json)?
解决方案
print "<pre>";
print_r(listFolders('../file_uploads/'));
function listFolders($dir)
{
$dh = scandir($dir);
$return = array();
foreach ($dh as $folder) {
if ($folder != '.' && $folder != '..') {
if (is_dir($dir . '/' . $folder)) {
$return[] = array(
'text' => $folder,
'children' => listFolders($dir . '/' . $folder)
);
}
}
}
return $return;
}