views:

181

answers:

1

Hi everybody,

I want to create a function that returns the full path from a set node, back to the root value. I tried to make a recursive function, but ran out of luck totally. What would be an appropriate way to do this? I assume that a recursive function is the only way?

Here's the array:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Root category
            [_parent] => 
        )

    [1] => Array
        (
            [id] => 2
            [name] => Category 2
            [_parent] => 1
        )

    [2] => Array
        (
            [id] => 3
            [name] => Category 3
            [_parent] => 1
        )

    [3] => Array
        (
            [id] => 4
            [name] => Category 4
            [_parent] => 3
        )
)

The result I want my function to output when getting full path of node id#4:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Root category
            [_parent] => 
        )

    [1] => Array
        (
            [id] => 3
            [name] => Category 3
            [_parent] => 1
        )

    [2] => Array
        (
            [id] => 4
            [name] => Category 4
            [_parent] => 3
        )
)

The notoriously bad example of my recursive skills:

    function recursive ($id, $array) {

        $innerarray = array();
        foreach ($array as $k => $v) {

            if ($v['id'] === $id) {
                if ($v['_parent'] !== '') {
                    $innerarray[] = $v;
                    recursive($v['id'], $array);
                }
            }

        }
        return $innerarray; 
    }

Thanks!

+3  A: 

assuming "id" in your sub array is that sub arrays index + 1 inside the parent array (otherwise you would need to do a search in the array each time), you could do this:

$searchNode = 4;
while ($searchNode)
{
    $result[] = $nodes[$searchNode - 1];
    $searchNode = $nodes[$searchNode - 1]["id"];
}
$result = array_reverse($result);
Oliver
Note that this does not check for loops or other 'errors' in the indexes.
Oliver