得到邻接表数据路径 [英] Get path from adjacency list data

查看:159
本文介绍了得到邻接表数据路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组(从邻接表中的数据),它看起来像:

 阵列

    [0] =>排列
        (
            [ID] => 1
            [名] =>周年
            [家长] => 0
        )    [1] =>排列
        (
            [ID] => 12
            [名] =>到达新
            [家长] => 1
        )    [2] =>排列
        (
            [ID] => 13
            [名] =>折扣
            [家长] => 12
        )    [3] =>排列
        (
            [ID] => 6
            [名] =>生日
            [家长] => 0
        )

和我正在寻找重新找回ID我路径的方式;

 例如:的getPath(13):Anniversary->新建arrives->折扣;
例如:的getPath(12):Anniversary->新建到达;
例如:的getPath(1):周​​年纪念;
例如:的getPath(6):生日;

我怎样才能做到这一点?
谢谢!


解决方案

 函数的getPath($ ID,$ ARR,$水平= 0){
    $结果=阵列();
    的foreach($改编为$关键=> $值){
        如果($ ID == $值['身份证']){
            $结果[] = $值['名'];
            的$ id = $值['父'];
            如果($编号!= 0){
              $结果= array_merge($结果的getPath($ ID,$ ARR,$级+ 1));
            }其他{
                打破;
            }
        }
    }
    返回$的水平? $结果:破灭(' - >',array_reverse($结果));
}
回声的getPath(13,$ ARR);

I have an array (data from adjacency table) and it looks like:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Anniversary
            [parent] => 0
        )

    [1] => Array
        (
            [id] => 12
            [name] => New arrives
            [parent] => 1
        )

    [2] => Array
        (
            [id] => 13
            [name] => Discount
            [parent] => 12
        )

    [3] => Array
        (
            [id] => 6
            [name] => Birthday
            [parent] => 0
        )
)

And I'm looking for the way to retrieve my path by ID;

For example: getPath(13): Anniversary->New arrives->Discount;
For example: getPath(12): Anniversary->New arrives;
For example: getPath(1): Anniversary;
For example: getPath(6): Birthday;

How can I do this? Thanks!

解决方案

function getpath($id, $arr, $level = 0) {
    $result = array();
    foreach($arr as $key => $value){
        if($id == $value['id']){
            $result[] = $value['name'];
            $id = $value['parent'];
            if($id != 0){
              $result = array_merge($result, getpath($id, $arr, $level+1));
            }else{
                break;
            }
        }
    }
    return $level ? $result : implode('->',array_reverse($result));
}
echo getpath(13,$arr);

这篇关于得到邻接表数据路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆