给定一个与叶节点位置相对应的值数组,我将如何访问该节点?
注意:我不熟悉有关树结构的术语。由于本人无知造成的疏忽,敬请谅解!
实际示例
给定一个这样的数组:
Array
(
[0] => 0
[1] => 2
[2] => 8
[3] => 9
)
可以在 $tree[2][8][9]
处找到带有键“9”的树节点(0 为根)。给定上面的数组,我如何在 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
提前致谢!
编辑:对于那些想知道的人,我的 findPathToRootNode
函数只是递归地查找父节点,并将其保存为上面找到的数组格式。如果有更好的方法来表示所述数据(特别是如果它解决了我的问题),那就更好了。
编辑:通读一遍,这个问题似乎与树无关,而是如何在单独的数组中访问给定其结构的数组。如此标记。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
制作一个自我定位功能。这应该可以解决问题(未经测试),
$tree
是数据,$tree
是数组的路径,$深度
本身就说明了一切。调用该函数
Make a self-targeting function. This should do the trick (untested)
With
$tree
being the data,$tree
the path to the array, and$depth
speaks for itself.Call the function with