Dynamic Array traversal in PHP

為{幸葍}努か 提交于 2019-11-29 15:16:54

I THINK you want:

function array_traverse($array, $key = null) {
    $out = (string) $key;
    if (isset($array[$key])) {
        $out = array_traverse($array, $array[$key]) . '/' . $out;
    }
    return $out;
}

Or, for a non-recursive method:

function array_traverse($array, $key = null) {
    $out = (string) $key;
    while(isset($array[$key])) {
        $out = $array[$key] . '/' . $out;
        $key = $array[$key];
    }
    return $out;
}

Yes, I would say isset() is the way to go:

traverse($array, $value) {
    $result = array();
    while (isset($array[$value])) {
        array_unshift($result, $value);
        # or just $result[] = $value if you want to append
        # instead of prepending
        $value = $array[$value];
    }
    return $result;
    # or return implode('/', traverse(array(...))),
    # but I always prefer array return types in such cases:
    # they are much more flexible to the users of the function
}

# BTW: Using implode will avoid having an unnecessary
# leading/trailing delimiter (slash in this case)
echo implode('/', traverse(array(...)));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!