天天看點

PHP遞歸擷取目錄内容readDir,遞歸删除rmdir

<pre name="code" class="php"><?php
/**
 * @param $path 需要讀取的目錄内容
 */
function readDirs($path, $deep=0) {
	//打開,讀取
	$handle = openDir($path);
	//循環獲得檔案
	while(false !== $file = readDir($handle)) {
		//是不是僞目錄 ., ..,是的話不處理
		if ($file == '.' || $file == '..') continue;


		echo str_repeat(' ', $deep*4), $file,'<br>';
		//判斷該檔案是否為目錄
		if(is_dir($path . '/' . $file)) {
			//是目錄,遞歸的擷取
			readDirs($path . '/' . $file, $deep+1);
		}
	}
	closeDir($handle);
}           

将擷取的目錄儲存起來,以便之後使用代碼如下

/**
 * @param $path 需要讀取的目錄内容
 *
 * @return array 很多元數組
 */
function readDirs($path, $deep=0) {
	$children = array();
	//打開,讀取
	$handle = openDir($path);
	//循環獲得檔案
	while(false !== $file = readDir($handle)) {
		//是不是僞目錄 ., ..,是的話不處理
		if ($file == '.' || $file == '..') continue;
		//記錄目前檔案資訊的數組
		$file_info['name']=$file;//檔案名
		//判斷該檔案是否為目錄
		if(is_dir($path . '/' . $file)) {
			//是目錄,遞歸的擷取
			$file_info['type'] = 'dir';
			$file_info['children'] = readDirs($path . '/' . $file, $deep+1);
		} else {
			$file_info['type'] = 'file';
		}
		$children[] = $file_info;
	}
	closeDir($handle);
	return $children;
}
           
/**
 * @param $path 删除需要目錄
 */
function rmDirs($path) {
	//打開,讀取
	$handle = openDir($path);
	//循環獲得檔案
	while(false !== $file = readDir($handle)) {
		//是不是僞目錄 ., ..,是的話不處理
		if ($file == '.' || $file == '..') continue;

		//判斷該檔案是否為目錄
		if(is_dir($path . '/' . $file)) {
			//是目錄,遞歸的擷取
			rmDirs($path . '/' . $file);
		} else {
			//檔案
			unlink($path . '/' . $file);//unlink删除檔案
		}
	}
	closeDir($handle);
	return rmdir($path);
}