使用PHP遍歷文件夾與子目錄的函數(shù)代碼
> 與更強(qiáng)力的 Glob() 函數(shù),作用是以數(shù)組的形式返回與指定模式相匹配的文件名或目錄。
> 友情提醒,千萬(wàn)別像小邪那樣在電腦前面呆太長(zhǎng)時(shí)間,否則就會(huì)像小邪一樣得見鬼的高血糖。
一. 遍歷單層文件夾:
> 在掃描單層文件夾的問題是,兩個(gè)函數(shù)的結(jié)果雖有不同,不過(guò)表現(xiàn)是相差不大的。
> Scandir 函數(shù)會(huì)提供額外兩行,分別是 “.” 和 “..” ,而 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 函數(shù)的表現(xiàn)好一點(diǎn),很準(zhǔn)確的說(shuō)。
> Scandir 函數(shù)會(huì)莫名其妙掃描兩次 ../ 處的文件,也就是說(shuō)如果小邪有倆文件。
> ../b.php 和 ../a.php,結(jié)果就會(huì)在掃描報(bào)告上面出現(xiàn)兩次,很是奇怪。
//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; //檢測(cè)目錄有效性
$allfiles = scandir($path); //獲取目錄下所有文件與文件夾
foreach ($allfiles as $filename) { //遍歷一遍目錄下的文件與文件夾
if (in_array($filename,array('.','..'))) continue; //無(wú)視 . 與 ..
$fullname = $path.'/'.$filename; //得到完整文件路徑
if (is_dir($fullname)) { //是目錄的話繼續(xù)遞歸
$result[$filename] = get_filetree_scandir($fullname); //遞歸開始
}
else {
$temp[] = $filename; //如果是文件,就存入數(shù)組
}
}
foreach ($temp as $tmp) { //把臨時(shí)數(shù)組的內(nèi)容存入保存結(jié)果的數(shù)組
$result[] = $tmp; //這樣可以讓文件夾排前面,文件在后面
}
return $result;
}
print_r(get_filetree_scandir($path));
> Glob 函數(shù)掃描灰常準(zhǔn)確,并且會(huì)自動(dòng)按照字母排好順序,貌似是最佳方案。
$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));
相關(guān)文章
PHP實(shí)現(xiàn)駝峰樣式字符串(首字母大寫)轉(zhuǎn)換成下劃線樣式字符串的方法示例
這篇文章主要介紹了PHP實(shí)現(xiàn)駝峰樣式字符串(首字母大寫)轉(zhuǎn)換成下劃線樣式字符串的方法,涉及php正則替換相關(guān)操作技巧,需要的朋友可以參考下2017-08-08PHP中curl_setopt函數(shù)用法實(shí)例分析
這篇文章主要介紹了PHP中curl_setopt函數(shù)用法,以實(shí)例形式分析了curl_setopt函數(shù)的功能、定義、用途及相關(guān)的使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04采用memcache在web集群中實(shí)現(xiàn)session的同步會(huì)話
這篇文章主要介紹了采用memcache在web集群中實(shí)現(xiàn)session的同步會(huì)話,需要的朋友可以參考下2014-07-07一個(gè)基于PDO的數(shù)據(jù)庫(kù)操作類
工作一年以來(lái),所做的項(xiàng)目使用的都是ADODB,但其的代碼臃腫和執(zhí)行效率低導(dǎo)致現(xiàn)在需要更換。2011-03-03Zend Framework上傳文件重命名的實(shí)現(xiàn)方法
這篇文章主要介紹了Zend Framework上傳文件重命名的實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Zend Framework上傳文件重命名的具體操作步驟與配置、檢測(cè)、重命名操作的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-11-11