给定一个与叶节点位置相对应的值数组,我将如何访问该节点?

发布于 2024-12-28 08:04:17 字数 866 浏览 1 评论 0原文

注意:我不熟悉有关树结构的术语。由于本人无知造成的疏忽,敬请谅解!

实际示例

给定一个这样的数组:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

扎心 2025-01-04 08:04:17

制作一个自我定位功能。这应该可以解决问题(未经测试),

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

$tree 是数据,$tree 是数组的路径,$深度 本身就说明了一切。

调用该函数

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文