所以我一直在尝试创建一个递归文件目录树列表函数。除了一些虫子,我大部分都有。例如重复的目录名,因为代码以及它在树中的深度不够。
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]
,这是不正确的。无论如何,只需要一个好的递归函数来列出数组中的所有文件,目录就是索引。
我不认为"$allFiles"变量应该是静态的。
此外,您使用的是一个未在任何地方定义的$currentPath变量。你试图用这个变量实现什么?
试试这段代码(它可能仍然不完美,但应该会给你足够的提示,告诉你如何进行真正的递归):
function ftpFileList($ftpConnection, $path="/") {
$files = array();
$contents = ftp_nlist($ftpConnection, $path);
foreach($contents as $currentFile) {
if($currentFile !== "." && $currentFile !== ".."){
if( strpos($currentFile,".") === false || strpos($currentFile,"." === 0) ) {
$files[$path][$currentFile] = ftpFileList($ftpConnection, $path.$currentFile.'/');
}else{
if($currentPath !== "." && $currentPath !== "..")
$files[$path][] = $currentFile;
}
}
}
return $files;
}
扩展我的评论中链接的答案,您可以将DirectoryIterator
与ftp://流包装结合使用
$fileData = fillArrayWithFileNodes( new DirectoryIterator( 'ftp://path/to/root' ) );
function fillArrayWithFileNodes( DirectoryIterator $dir )
{
$data = array();
foreach ( $dir as $node )
{
if ( $node->isDir() && !$node->isDot() )
{
$data[$node->getFilename()] = fillArrayWithFileNodes( new DirectoryIterator( $node->getPathname() ) );
}
else if ( $node->isFile() )
{
$data[] = $node->getFilename();
}
}
return $data;
}