Поэтому я пытался создать рекурсивную функцию отображения дерева каталогов. У меня есть большая часть, кроме некоторых ошибок. Такие, как дубликаты имен каталогов из-за кода, а также не углубляются в дерево.
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://stream
$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;
}