0

我正在尝试递归遍历一组包含要上传的文件或另一个目录以检查要上传的文件的目录。

到目前为止,我正在让我的脚本深入文件系统 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我都有我开始的基本路径加上我正在扫描的目录的当前名称。但是我缺少介于两者之间的中间文件夹。如何将完整的当前文件路径保持在范围内?

4

2 回答 2

1

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

使用堆栈来保存中间路径(通常会在堆上),而不是使用更多的系统堆栈(它必须保存路径以及整个帧),扫描大型目录树可能更有效函数调用的下一级。

于 2013-05-03T01:28:58.353 回答
0

Thank you. Yes, I needed to build the full path inside the function. Here is the version that works:

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;

}
于 2013-05-04T07:54:52.027 回答