[英]Given an array of values corresponding to the location of a leaf node, how would I access said node?
Note: I am unfamiliar with terminology regarding tree structures. 注意:我不熟悉有关树结构的术语。 Please forgive any oversights that may be a result of my ignorance!
请原谅我的无知造成的疏忽!
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). 可以在
$tree[2][8][9]
(以0为根)处找到具有键“ 9”的树节点。 Given the above array, how would I construct a statement in PHP that would access the leaf node? 给定上述数组,我将如何在PHP中构造一个可访问叶节点的语句?
/*
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. 编辑 :对于那些想知道,我的
findPathToRootNode
函数只是递归地找到父节点,并将其保存为上面找到的数组格式。 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.
这样标记。
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. 以
$tree
为数据, $tree
为数组的路径,而$depth
说明一切。
Call the function with 用调用函数
$leaf = getLeaf($tree,$targetleaf);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.