使用PHP遍曆檔案夾與子目錄的函數代碼_php技巧

來源:互聯網
上載者:User
我們要使用的函數有 Scandir,它的作用是列出指定路徑中的檔案和目錄,就像 Dir 一樣。


> 與更強力的 Glob() 函數,作用是以數組的形式返回與指定模式相匹配的檔案名稱或目錄。
> 友情提醒,千萬別像小邪那樣在電腦前面呆太長時間,否則就會像小邪一樣得見鬼的高血糖。

一. 遍曆單層檔案夾:

> 在掃描單層檔案夾的問題是,兩個函數的結果雖有不同,不過表現是相差不大的。
> Scandir 函數會提供額外兩行,分別是 “.” 和 “..” ,而 Glob 則是沒有的。

複製代碼 代碼如下:

function get_dir_scandir(){
$tree = array();
foreach(scandir('./') as $single){
echo $single."<br/>\r\n";
}
}
get_dir_scandir();

function get_dir_glob(){
$tree = array();
foreach(glob('./*') as $single){
echo $single."<br/>\r\n";
}
}
get_dir_glob();

二. 遞迴遍曆檔案樹:

> 在遞迴掃描資料夾樹狀目錄的問題上,還是 Glob 函數的表現好一點,很準確的說。
> Scandir 函數會莫名其妙掃描兩次 ../ 處的檔案,也就是說如果小邪有倆檔案。
> ../b.php 和 ../a.php,結果就會在掃描報告上面出現兩次,很是奇怪。
複製代碼 代碼如下:

//Update at 2010.07.25 - 以下代碼作廢
$path = '..';
function get_filetree_scandir($path){
$tree = array();
foreach(scandir($path) as $single){
if(is_dir('../'.$single)){
$tree = array_merge($tree,get_filetree($single));
}
else{
$tree[] = '../'.$single;
}
}
return $tree;
}
print_r(get_filetree_scandir($path));

//Update at 2010.07.25 - 以下為新代碼
$path = './';
function get_filetree_scandir($path){
$result = array();
$temp = array();
if (!is_dir($path)||!is_readable($path)) return null; //檢測目錄有效性
$allfiles = scandir($path); //擷取目錄下所有檔案與檔案夾
foreach ($allfiles as $filename) { //遍曆一遍目錄下的檔案與檔案夾
if (in_array($filename,array('.','..'))) continue; //無視 . 與 ..
$fullname = $path.'/'.$filename; //得到完整檔案路徑
if (is_dir($fullname)) { //是目錄的話繼續遞迴
$result[$filename] = get_filetree_scandir($fullname); //遞迴開始
}
else {
$temp[] = $filename; //如果是檔案,就存入數組
}
}
foreach ($temp as $tmp) { //把臨時數組的內容存入儲存結果的數組
$result[] = $tmp; //這樣可以讓檔案夾排前面,檔案在後面
}
return $result;
}
print_r(get_filetree_scandir($path));

> Glob 函數掃描灰常準確,並且會自動按照字母排好順序,貌似是最佳方案。
複製代碼 代碼如下:

$path = '..';
function get_filetree($path){
$tree = array();
foreach(glob($path.'/*') as $single){
if(is_dir($single)){
$tree = array_merge($tree,get_filetree($single));
}
else{
$tree[] = $single;
}
}
return $tree;
}
print_r(get_filetree($path));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.