PHP實現遞迴目錄的5種方法_php執行個體

來源:互聯網
上載者:User

項目開發中免不了要在伺服器上建立檔案夾,比如上傳圖片時的目錄,模板解析時的目錄等。這不當前手下的項目就用到了這個,於是總結了幾個迴圈建立目錄的方法。

方法一:使用glob迴圈

<?php//方法一:使用glob迴圈 function myscandir1($path, &$arr) {   foreach (glob($path) as $file) {    if (is_dir($file)) {      myscandir1($file . '/*', $arr);    } else {       $arr[] = realpath($file);    }  }}?>

方法二:使用dir && read迴圈

<?php//方法二:使用dir && read迴圈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迴圈

<?php//方法三:使用opendir && readdir迴圈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迴圈
 

<?php//方法四:使用scandir迴圈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迴圈

 <?php//方法五:使用SPL迴圈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測試回合時間

<?phpmyscandir1('./Code',$arr1);//0.164010047913 myscandir2('./Code',$arr2);//0.243014097214 myscandir3('./Code',$arr3);//0.233012914658 myscandir4('./Code',$arr4);//0.240014076233myscandir5('./Code',$arr5);//0.329999923706  //需要安裝xdebugecho xdebug_time_index(), "\n";?>

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.