3

I want to build a hierarchy from a one-dimensional array and can (almost) do so with a more or less hardcoded code. How can I make the code dynamic?

Perhaps with while(isset($array[$key])) { ... }? Or, with an extra function? Like this: $out = my_extra_traverse_function($array,$key);

function array_traverse($array,$key=NULL) {
    $out = (string) $key;
    $out = $array[$key] . "/" . $out;

    $key = $array[$key];
    $out = $array[$key] ? $array[$key] . "/" . $out : "";
    $key = $array[$key];
    $out = $array[$key] ? $array[$key] . "/" . $out : "";
    $key = $array[$key];
    $out = $array[$key] ? $array[$key] . "/" . $out : "";

    return $out;
}

$a = Array(102=>101, 103=>102, 105=>107, 109=>105, 111=>109, 104=>111);
echo array_traverse($a,104);

Output: 107/105/109/111/104

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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(...)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.