Given an array of values corresponding to the location of a leaf node, how would I access said node?

73 views Asked by At

Note: I am unfamiliar with terminology regarding tree structures. Please forgive any oversights that may be a result of my ignorance!

Practical Example

Given an array as such:

Array
(
    [0] => 0
    [1] => 2
    [2] => 8
    [3] => 9
)

The tree node with the key "9" would be found at $tree[2][8][9] (with 0 being the root). Given the above array, how would I construct a statement in PHP that would access the leaf node?

Target Code

/*
    Let's say I am given a $leafNodeID of 9, and I'd like to save some
    data ($dataToSave) into said leaf node
*/
$leafNodeID = 9;
$dataToSave = array("name" => "foobar");
$tree_path = $this->findPathToRootNode($tree, $leafNodeID);    // This returns the array found above.
${?????} = $dataToSave;     // <-- Here be dragons

Thanks in advance!

Edit: For those wondering, my findPathToRootNode function just recursively finds the parent node, and saves it in the array format found above. If there's a better way to represent said data (especially if it solves my problem), that would be even better.

Edit: On a read through, it seems this question is less about trees, but rather how to access an array given its structure in a separate array. Tagging as such.

1

There are 1 answers

2
Rene Pot On

Make a self-targeting function. This should do the trick (untested)

function getLeaf($tree, $targetleaf, $depth = 0){
    if (isset($targetleaf[$depth+1])
        return getLeaf($tree[$targetleaf[$depth]], $targetleaf, $depth + 1)
    else
        return $tree[$depth];
}

With $tree being the data, $tree the path to the array, and $depth speaks for itself.

Call the function with

$leaf = getLeaf($tree,$targetleaf);