2013-05-03 73 views
0

我试图递归迭代通过一组包含要上传的文件或另一个目录以检查要上载的文件的目录。PHP中的文件路径和递归

到目前为止,我得到我的脚本去2层深入到文件系统,但我还没有想出一个办法,以保持我目前的完整文件路径范围为我的功能:

function getPathsinFolder($basepath = null) { 

    $fullpath = 'www/doc_upload/test_batch_01/'; 

    if(isset($basepath)): 
     $files = scandir($fullpath . $basepath . '/'); 
    else: 
     $files = scandir($fullpath); 
    endif; 

    $one = array_shift($files); // to remove . & .. 
    $two = array_shift($files); 

    foreach($files as $file): 
     $type = filetype($fullpath . $file); 
     print $file . ' is a ' . $type . '<br/>'; 

     if($type == 'dir'): 

      getPathsinFolder($file); 

     elseif(($type == 'file')): 

      //uploadDocsinFolder($file); 

     endif; 

    endforeach; 

} 

所以,每次我打电话getPathsinFolder我有我开始的基本路径加上我正在scandirring目录的当前名称。但我错过了中间的中间文件夹。如何保持完整的当前文件路径在范围内?

+0

您可以使用[ RecursiveDirectoryIterator](http://www.php.net/manual/en/recursivedirectoryiterator.construct.php)class – 2013-05-03 01:50:06

回答

1

很简单。如果你想递归,你需要在调用getPathsinFolder()时将整个路径作为参数传递。

使用堆栈来保存中间路径(通常会放在堆上),而不是使用更多的系统堆栈(它必须保存路径以及对于函数调用的下一级的整体框架

+0

感谢spamsink。你的回答让我做了th在下面修复。我会考虑使用堆栈。 PHP在SPL库中有一个SplStack类,但到现在为止还没有做过太多的SPL。我也想过使用RecursiveDirectoryIterator对象,但我不清楚如何正确实现。 – shotdsherrif 2013-05-04 07:58:36

0

谢谢是的,我需要建立在函数内部的完整路径下面是作品的版本:。

function getPathsinFolder($path = null) { 

    if(isset($path)): 
     $files = scandir($path); 
    else: // Default path 
     $path = 'www/doc_upload/'; 
     $files = scandir($path); 
    endif; 

    // Remove . & .. dirs 
    $remove_onedot = array_shift($files); 
    $remove_twodot = array_shift($files); 
    var_dump($files); 

    foreach($files as $file): 
     $type = filetype($path . '/' . $file); 
     print $file . ' is a ' . $type . '<br/>'; 
     $fullpath = $path . $file . '/'; 
     var_dump($fullpath); 

     if($type == 'dir'): 
      getPathsinFolder($fullpath); 
     elseif(($type == 'file')): 
      //uploadDocsinFolder($file); 
     endif; 

    endforeach; 

}