计算路径a对于路径b的相对路径

57 篇文章 3 订阅

---CSDN的这个格式实在DT-_-

<?php
/**
 * 计算路径a对于路径b的相对路径
 * @author wusuopubupt
 * @date 2013-08-01
 * */
$dira = '/a/e.php';
$dirb = '/a/b/f/e/g.php';

//explode directions
$arr_dira = explode('/', $dira);
$arr_dirb = explode('/', $dirb);

$count_a = count($arr_dira);
$count_b = count($arr_dirb);
$max = max($count_a,$count_b);

$count =0;
for ($i = 0 ; $i<$max ; $i++) {
    if(isset($arr_dira[0]) && isset($arr_dirb[0]) && $arr_dira[0] == $arr_dirb[0]){
        array_shift($arr_dira);
        array_shift($arr_dirb);
        $count ++;
    }
}

$relative_path = str_repeat('../', $count_a - $count);
echo $relative_path . implode('/', $arr_dirb) . "\n";
?>

基本思路:先把a,b2个路径用/分割成数组,定义count = 0;从下标为0开始遍历2个数组,如果arr_a[0] == arr_b[0],那就用array_shift()删除数组第一个值,此时count+1,继续循环直到不相等,此时数组b只剩下a,b不相同的部分。用数组a的长度减去count,就是路径a 到达a,b共同路径的次数。比如2次,就用../../表示,然后,用/连接数组b,即可得到a相对于b的路径
参考:
1.启发的但是有错误的算法: http://istrone.com/?p=1165
2.array_pop 用法: http://www.php.net/manual/zh/function.array-pop.php
3.array_shift用法:http://www.php.net/manual/zh/function.array-shift.php
4.array_diff():计算2个数组的差集
  array_intersect():交集

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值