Dynamic Array traversal in PHP

Posted by Kristoffer Bohmann on Stack Overflow See other posts from Stack Overflow or by Kristoffer Bohmann
Published on 2010-05-28T16:41:01Z Indexed on 2010/05/28 16:41 UTC
Read the original article Hit count: 259

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about php

Related posts about array