PHP中的文件路径和递归
我试图递归地遍历一组dir,这些dir包含要上载的文件或另一个dir来检查要上载的文件 到目前为止,我正在让我的脚本深入到文件系统的两个级别,但我还没有找到一种方法来保持我当前的完整文件路径在我的功能范围内:PHP中的文件路径和递归,php,recursion,filesystems,Php,Recursion,Filesystems,我试图递归地遍历一组dir,这些dir包含要上载的文件或另一个dir来检查要上载的文件 到目前为止,我正在让我的脚本深入到文件系统的两个级别,但我还没有找到一种方法来保持我当前的完整文件路径在我的功能范围内: function getPathsinFolder($basepath = null) { $fullpath = 'www/doc_upload/test_batch_01/'; if(isset($basepath)): $files = scand
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($basepath=null){
$fullpath='www/doc_upload/test_batch_01/';
如果(isset($basepath)):
$files=scandir($fullpath.$basepath.'/');
其他:
$files=scandir($fullpath);
endif;
$one=array_shift($files);//要删除。&。。
$two=数组移位($files);
foreach($files作为$file):
$type=filetype($fullpath.$file);
打印$file。'是一种“$type”。; 如果($type=='dir'): getPathsinFolder($file); elseif(($type=='file')): //上传docsinfolder($file); endif; endforeach; }
因此,每次我调用
getPathsinFolder
时,我都会得到我开始使用的基本路径加上我正在扫描的目录的当前名称。但我缺少中间文件夹。如何在作用域中保留完整的当前文件路径?非常简单。如果需要递归,则需要在调用getPathsinFolder()时将整个路径作为参数传递
使用堆栈来保存中间路径(通常在堆上),而不是使用更多的系统堆栈,扫描大型目录树可能更有效(它必须为下一级函数调用保存路径和整个框架。谢谢。是的,我需要在函数内部构建完整路径。以下是有效的版本:
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;
}
函数getPathsinFolder($path=null){
如果(isset($path)):
$files=scandir($path);
else://默认路径
$path='www/doc_upload/';
$files=scandir($path);
endif;
//删除.&..dirs
$remove\u onedot=array\u shift($files);
$remove\u twodot=array\u shift($files);
var_dump($files);
foreach($files作为$file):
$type=filetype($path.'/'.$file);
打印$file。'是一种“$type”。; $fullpath=$path.$file.'/'; var_dump($fullpath); 如果($type=='dir'): getPathsinFolder($fullpath); elseif(($type=='file')): //上传docsinfolder($file); endif; endforeach; }
您可以使用ClassThank spamsink。您的回答让我做了下面的修复。我将研究如何使用堆栈。PHP在SPL库中有一个SplStack类,但到目前为止还没有对SPL做太多的工作。我还想过使用递归DirectoryIterator对象,但我不清楚如何正确实现。