《PHP編程:PHP實現(xiàn)遞歸目錄的5種方法》要點:
本文介紹了PHP編程:PHP實現(xiàn)遞歸目錄的5種方法,希望對您有用。如果有疑問,可以聯(lián)系我們。
項目開發(fā)中免不了要在服務(wù)器上創(chuàng)建文件夾,比如上傳圖片時的目錄,模板解析時的目錄等.這不當(dāng)前手下的項目就用到了這個,于是總結(jié)了幾個循環(huán)創(chuàng)建目錄的方法.
PHP實戰(zhàn)
方法一:使用glob循環(huán)
PHP實戰(zhàn)
<?php //方法一:使用glob循環(huán) function myscandir1($path, &$arr) { foreach (glob($path) as $file) { if (is_dir($file)) { myscandir1($file . '/*', $arr); } else { $arr[] = realpath($file); } } } ?>
方法二:使用dir && read循環(huán)
PHP實戰(zhàn)
<?php //方法二:使用dir && read循環(huán) function myscandir2($path, &$arr) { $dir_handle = dir($path); while (($file = $dir_handle->read()) !== false) { $p = realpath($path . '/' . $file); if ($file != "." && $file != "..") { $arr[] = $p; } if (is_dir($p) && $file != "." && $file != "..") { myscandir2($p, $arr); } } } ?>
方法三:使用opendir && readdir循環(huán)
PHP實戰(zhàn)
<?php //方法三:使用opendir && readdir循環(huán) function myscandir3($path, &$arr) { $dir_handle = opendir($path); while (($file = readdir($dir_handle)) !== false) { $p = realpath($path . '/' . $file); if ($file != "." && $file != "..") { $arr[] = $p; } if (is_dir($p) && $file != "." && $file != "..") { myscandir3($p, $arr); } } } ?>
?方法四:使用scandir循環(huán)
?PHP實戰(zhàn)
<?php //方法四:使用scandir循環(huán) function myscandir4($path, &$arr) { $dir_handle = scandir($path); foreach ($dir_handle as $file) { $p = realpath($path . '/' . $file); if ($file != "." && $file != "..") { $arr[] = $p; } if (is_dir($p) && $file != "." && $file != "..") { myscandir4($p, $arr); } } } ?>
方法五:使用SPL循環(huán)
PHP實戰(zhàn)
<?php //方法五:使用SPL循環(huán) function myscandir5($path, &$arr) { $iterator = new DirectoryIterator($path); foreach ($iterator as $fileinfo) { $file = $fileinfo->getFilename(); $p = realpath($path . '/' . $file); if (!$fileinfo->isDot()) { $arr[] = $p; } if ($fileinfo->isDir() && !$fileinfo->isDot()) { myscandir5($p, $arr); } } } ?>
?可以用xdebug測試運行時間
PHP實戰(zhàn)
<?php myscandir1('./Code',$arr1);//0.164010047913 myscandir2('./Code',$arr2);//0.243014097214 myscandir3('./Code',$arr3);//0.233012914658 myscandir4('./Code',$arr4);//0.240014076233 myscandir5('./Code',$arr5);//0.329999923706 //需要安裝xdebug echo xdebug_time_index(), "\n"; ?>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持維易PHP.PHP實戰(zhàn)
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/2937.html