PHP多次调用循环函数的最佳方法
我有一个特定的目录,其中可能包含PHP多次调用循环函数的最佳方法,php,loops,foreach,Php,Loops,Foreach,我有一个特定的目录,其中可能包含zip文件 我想循环遍历目录的每个子元素,以检查这是否是一个zip文件。然后把它解开。然后处理其他文件 我习惯于处理我的文件 所以我选择了这个 $contents = $this->manager->listContents('local://my_directory , true); foreach ($contents as $file) { if( $file['extension'] == 'zip') //Unzip in sa
zip
文件
我想循环遍历目录的每个子元素,以检查这是否是一个zip文件。然后把它解开。然后处理其他文件
我习惯于处理我的文件
所以我选择了这个
$contents = $this->manager->listContents('local://my_directory , true);
foreach ($contents as $file) {
if( $file['extension'] == 'zip')
//Unzip in same location
}
问题是解压的文件不在循环中,如果是zip文件,则包含另一个zip。第二个永远不会解开拉链
所以我想了想
function loopAndUnzip(){
$contents = $this->manager->listContents('local_process://' . $dir['path'] , true);
foreach ($contents as $file) {
if( $file['extension'] == 'zip')
//Unzip and after call loopAndUnzip()
}
}
但是,如果zip中有zip,那么初始函数将永远不会完成,并且会被反复调用。
这不是性能问题吗
如何管理这类事情?
loopAndUnzip
将再次执行所有文件,因此您只需再次解压缩相同的zipfile,然后无限期地重新开始整个文件夹
一些可能性:
$contents
时,保留一个单独的数组,并具有类似以下内容:可以使用glob查找它们,并使函数递归。您可以从某个目录开始,将所有文件解压缩到该目录中,并检查是否有新的拉链。
我建议也使用递归目录。如果
A.zip
和B.zip
都有一个名为example.txt
的文件,它将被覆盖。对于dirs,它不会:
function unzipAll(string $dirToScan = "/someDir", $depth=0):void {
if($depth >10 ){
throw new Exception("Maximum zip depth reached");
}
$zipfiles = glob($dirToScan."*.zip");
// Unzip all zips found this round:
foreach ($zipfiles as $zipfile) {
$zipLocation = "/".$zipname;
// unzip here to $zipLocation
// and now check if in the zip dir there is stuff to unzip:
unzipAll($dirToScan.$zipLocation, ++$depth);
}
}
$depth是可选的,但这样你就不能把自己炸死。第一行有语法错误。缺少报价。荧光灯把它给人了。从外观上看,您的实际代码中不存在此错误,但您可能希望修复此错误,以阻止对其进行解答。如果您将每个zipfile解包到一个子文件夹中,则此错误可能会起作用,但OP说的位置相同。我已添加了使用子文件夹的原因:)是的。一个很好的理由。如果需求允许的话,它确实更安全代码>在函数调用之前,否则深度总是
0
。否则它工作得很好,谢谢你!相当确定的是,$depth++
应该可以工作。将其更改为+1
,无需在循环外执行。
function unzipAll(string $dirToScan = "/someDir", $depth=0):void {
if($depth >10 ){
throw new Exception("Maximum zip depth reached");
}
$zipfiles = glob($dirToScan."*.zip");
// Unzip all zips found this round:
foreach ($zipfiles as $zipfile) {
$zipLocation = "/".$zipname;
// unzip here to $zipLocation
// and now check if in the zip dir there is stuff to unzip:
unzipAll($dirToScan.$zipLocation, ++$depth);
}
}