PHP實作遞歸目錄的5種方法

墨辰丷
發布: 2023-03-28 15:42:01
原創
1710 人瀏覽過

本篇文章主要介紹了PHP實作遞歸目錄的5種方法,主要是利用一些循環來實現的,有興趣的小夥伴們可以參考一下。

專案開發中免不了要在伺服器上建立資料夾,例如上傳圖片時的目錄,模板解析時的目錄等。這不當前手下的專案就用到了這個,於是總結了幾個循環創建目錄的方法。

方法一:使用glob循環

#
<?php
//方法一:使用glob循环
 
function myscandir1($path, &$arr) {
 
  foreach (glob($path) as $file) {
    if (is_dir($file)) {
      myscandir1($file . &#39;/*&#39;, $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 . &#39;/&#39; . $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 . &#39;/&#39; . $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 . &#39;/&#39; . $file);
    if ($file != "." && $file != "..") {
      $arr[] = $p;
    }
    if (is_dir($p) && $file != "." && $file != "..") {
      myscandir4($p, $arr);
    }
  }
}
 ?>
登入後複製


#方法五:使用SPL迴圈


# 可以用xdebug測試運行時間


<?php
myscandir1(&#39;./Code&#39;,$arr1);//0.164010047913 
myscandir2(&#39;./Code&#39;,$arr2);//0.243014097214 
myscandir3(&#39;./Code&#39;,$arr3);//0.233012914658 
myscandir4(&#39;./Code&#39;,$arr4);//0.240014076233
myscandir5(&#39;./Code&#39;,$arr5);//0.329999923706
 
 
//需要安装xdebug
echo xdebug_time_index(), "\n";
?>
登入後複製

以上就是本文的全部內容,希望對大家的學習有幫助。

相關推薦:

PHP實作的Redis多庫選擇功能單例類別(詳解)

######PHP自訂函數判斷是否為Get/Post/Ajax提交的方法詳解###################php###自動備份資料庫表的方法###########################

以上是PHP實作遞歸目錄的5種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!