愛悠閑 > 目錄遞歸和相對路徑函數

目錄遞歸和相對路徑函數

分類: PHP技術文檔  |  標簽: path,function,file  |  作者: liangguohuan 相關  |  發布日期 : 2015-11-23  |  熱度 : 751°

獲取兩個文件相對路徑,例如:
$a = '/a/b/c/d/e.php'; $b = '/a/b/12/34/c.php';
計算出 $b 相對于 $a 的相對路徑應該是 ../../c/d


方法一:

function getRelativePath($a, $b) {
    for($i=0;$i<strlen($a);$i++) {
        if($a{$i} !== $b{$i}) {
            $stra = substr($a, $i);
            $strb = substr($b, $i);
            break;
        }
    }
    $arra = explode("/", $stra);
    $arrb = explode("/", $strb);
    $str = str_repeat("../", count($arrb) - 1) . implode("/", array_splice($arra, 0, count($arra) -1));
    return $str;
}


方法二

function get_path($path1, $path2)
{
	$path1 = trim($path1, "/");
	$path2 = trim($path2, "/");
	$arr = explode("/", $path1);
	$index = -1;
	foreach ($arr as $val)
	{
		if(@strpos($path2, $val) > -1)
		{
			$path2 = str_replace("/{$val}", "", $path2);
			$index++;
		}
	}
	//echo count($arr);
	$dir = $index == count($arr)-1 ? "" : implode("/", array_slice($arr, $index, count($arr) - $index - 1));
	$arr2 = explode("/", $path2);
	$count = count($arr2) -1;
	$updir = "";
	for ($i=0; $i<$count; $i++)
	{
		$updir .= "../";
	}
	return $updir.$dir;
}

目錄遞歸讀取

方法-:

function getFiles($dir, $i=-1) {
	$arrRec = array();
	$dir = rtrim($dir, "/") . "/";
	if(is_dir($dir)){
		$i++;
		echo str_repeat(" ", $i*3), "|-", trim(strrchr(trim($dir, "/"), "/"), "/"), "\n";
		$arr = glob($dir . "*");
		foreach ($arr as $value) {
			if (is_dir($value . "/")) {
				$arrRec[$value] = getFiles($value, $i);
			}
			else {
				$arrRec[] = $value;
				echo str_repeat(" ", $i*3), "|-", trim(strrchr(trim($value, "/"), "/"), "/"), "\n";
			}
		}
	}
	return $arrRec;
}

方法二:
function getFiles2($dir, $i=-1){
	$arrRec = array();
	$dir = rtrim($dir, "/") . "/";
	if(is_dir($dir)){
		$i++;
		echo str_repeat(" ", $i*3), "|-", trim(strrchr(trim($dir, "/"), "/"), "/"), "\n";
		$arr = scandir($dir);
		if($arr){
			foreach ($arr as $value){
				if($value == "." || $value == "..") {
					continue;
				}
				else if(is_dir($dir.$value)) {
					$arrRec[$dir.$value] = getFiles2($dir.$value, $i);
				}
				else {
					$arrRec[] = $value;
					echo str_repeat(" ", $i*3), "|-", $value, "\n";
				}
			}
		}
	}
	return $arrRec;
}

方法三:
function getFiles3($dir, $i=-1)
{
	$arrRec = array();
	$dir = rtrim($dir, "/") . "/";
	if ( $handle = opendir($dir) ) {
		$i++;
        echo str_repeat(" ", $i*3), "|-", trim(strrchr(trim($dir, "/"), "/"), "/"), "\n";
		while ( ($file = readdir($handle)) !== false ) {
			if ( $file != ".." && $file != "." ) {
				if ( is_dir($dir.$file) ) {
					$arrRec[$dir.$file] = getFiles3($dir . "/" . $file, $i);
				}else {
					$arrRec[] = $file;
					echo str_repeat(" ", $i*3), "|-", $file, "\n";
				}
			}
		}
		closedir($handle);
		return $arrRec;
	}
}


快乐彩中奖说明