【发布时间】:2015-01-05 10:14:09
【问题描述】:
所以我一直在尝试创建一个递归文件目录树列表函数。我有大部分,除了一些错误。例如由于代码而导致的目录名称重复以及它在树中的深度不够。
function ftpFileList($ftpConnection, $path="/") {
static $allFiles = array();
$contents = ftp_nlist($ftpConnection, $path);
foreach($contents as $currentFile) {
if($currentFile !== "." && $currentFile !== ".."){
if( strpos($currentFile,".") === false || strpos($currentFile,"." === 0) ) {
if(!$allFiles[$path][$currentFile]){
$allFiles[$path][$currentFile] = array();
}
ftpFileList($ftpConnection,$currentFile);
}else{
if($currentPath !== "." && $currentPath !== "..") $allFiles[$path][] = $currentFile;
}
}
}
return $allFiles;
}
返回的数组和这个类似
array(3) {
[""]=>
array(4) {
[0]=>
string(9) ".ftpquota"
[1]=>
string(9) ".htaccess"
["kms"]=>
array(0) {
}
["public_html"]=>
array(0) {
}
}
["kms"]=>
array(6) {
[0]=>
string(16) "admin_config.php"
[1]=>
string(8) "css.json"
[2]=>
string(10) "pages.json"
["php_includes"]=>
array(0) {
}
["site"]=>
array(0) {
}
["templates"]=>
array(0) {
}
}
["public_html"]=>
array(20) {
[0]=>
string(9) ".htaccess"
[1]=>
string(7) "404.php"
...
}
}
基本上我想做的就是得到这样的东西
.htaccess
.ftpquota
-public_html
-folder2
-folder3
file.ext
file2.ext
-kms
-folder4
file3.ext
-folder5
-file4.ext
file5.ext
希望你能理解我的要求,只需要看看这里出了什么问题,以及如何获得正确的索引来放置$currentFile,因为它正在搜索$allFiles[$path][$currentFile],这不会是正确的。无论如何只需要一个好的递归函数来列出数组中的所有文件,目录是索引。
【问题讨论】:
-
@Jonathan - 是不是有点不同,因为它是针对远程服务器的。必须实现一些功能来查看远程目录项是子文件夹还是文件。 ftp_nlist 手册有一些例子php.net/manual/ru/function.ftp-nlist.php
-
'/path/to/root/' 在链接的答案中可以是一个流(例如 ftp),它不必位于任何特定的物理位置
标签: php arrays recursion multidimensional-array