虽然来晚了,但是基于被接受的答案继续建立...
如果你想要将所有文件和目录作为数组(可以在javascript中使用JSON.stringify进行美化),你可以修改函数如下:
function listFolderFiles($dir) {
$arr = array();
$ffs = scandir($dir);
foreach($ffs as $ff) {
if($ff != '.' && $ff != '..') {
$arr[$ff] = array();
if(is_dir($dir.'/'.$ff)) {
$arr[$ff] = listFolderFiles($dir.'/'.$ff);
}
}
}
return $arr;
}
针对新手...
要使用上述的JSON.stringify
,你的JS/jQuery代码应该是这样的:
var ajax = $.ajax({
method: 'POST',
data: {list_dirs: true}
}).done(function(msg) {
$('pre').html(
'FILE LAYOUT<br/>' +
JSON.stringify(JSON.parse(msg), null, 4)
);
});
假设您的HTML中有一个<pre>
元素。任何类型的AJAX都可以,但我认为大多数人都在使用类似于上面的jQuery。
还有相应的PHP代码:
if(isset($_POST['list_dirs'])) {
echo json_encode(listFolderFiles($rootPath));
exit();
}
在之前您已经有了listFolderFiles
。
在我的情况下,我已将$rootPath
设置为站点的根目录...
$rootPath;
if(!isset($rootPath)) {
$rootPath = $_SERVER['DOCUMENT_ROOT'];
}
最终结果类似于...
| some_file_1487.smthng []
| some_file_8752.smthng []
| CSS
| | some_file_3615.smthng []
| | some_file_8151.smthng []
| | some_file_7571.smthng []
| | some_file_5641.smthng []
| | some_file_7305.smthng []
| | some_file_9527.smthng []
|
| IMAGES
| | some_file_4515.smthng []
| | some_file_1335.smthng []
| | some_file_1819.smthng []
| | some_file_9188.smthng []
| | some_file_4760.smthng []
| | some_file_7347.smthng []
|
| JSScripts
| | some_file_6449.smthng []
| | some_file_7864.smthng []
| | some_file_3899.smthng []
| | google-code-prettify
| | | some_file_2090.smthng []
| | | some_file_5169.smthng []
| | | some_file_3426.smthng []
| | | some_file_8208.smthng []
| | | some_file_7581.smthng []
| | | some_file_4618.smthng []
| |
| | some_file_3883.smthng []
| | some_file_3713.smthng []
... and so on...
注意:你的代码看起来不会完全像这样 - 我修改了JSON.stringify
函数以显示制表符(竖线),对齐所有键值,去掉键上的引号等。如果我有时间上传或者有足够的兴趣,我会在回答中提供一个链接。