gpt4 book ai didi

php - 节点链接树和数据由 PHP 在 json 文件中填充

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:25:56 26 4
gpt4 key购买 nike

我使用这里的嵌套集模型:http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/以及来自 Depth of a Sub-Tree 部分的查询。

我想使用这张图 http://bl.ocks.org/mbostock/4339184使用我数据库中的数据,但我不知道如何在 PHP 中设计算法来编写 json 数据。flare.json 在这里 http://bl.ocks.org/mbostock/raw/4063550/flare.json (我没有使用 size 属性)

我写了一些代码,但我迷路了,我不知道该怎么做:

$subtree = array(
['name' => 'ELECTRONICS', 'depth' => 0],
['name' => 'TELEVISIONS', 'depth' => 1],
['name' => 'TUBE', 'depth' => 2],
['name' => 'LCD', 'depth' => 2],
['name' => 'PLASMA', 'depth' => 2],
['name' => 'PORTABLE ELECTRONICS', 'depth' => 1],
['name' => 'MP3 PLAYERS', 'depth' => 2],
['name' => 'FLASH', 'depth' => 3],
['name' => 'CD PLAYERS', 'depth' => 2],
['name' => '2 WAY RADIOS', 'depth' => 2],
);

function buildTree($data) {
$tree = [];
$current = 0;

foreach ($data as $key => $child) {
// Root
if ($key == $current) {
$tree['name'] = $child['name'];
$lastLevel = $child['depth'];
// Child
} elseif( && $child['depth'] == ($lastLevel + 1)) {
if (!isset($tree['children'])) {
$tree['children'] = [];
}
$tree['children'][] = buildTree(array_slice($data, $key));
$current++;
}
}

return $tree;
}

$tree = buildTree($subtree);

print_r($tree);

非常感谢您的帮助!

最佳答案

您需要能够在到达“非子级”时通过返回到目前为止的结果来停止递归循环。此外,您不需要 $current,因为在每个递归循环中,您的数组都被切片并且第一个 $key 始终为 0:

function buildTree($data) {

$tree = array();

foreach ($data as $key => $child) {
// Root
if ($key == 0){
$tree['name'] = $child['name'];
$lastLevel = $child['depth'];
// Child
} else if(($child['depth'] == ($lastLevel + 1))) {
if (!isset($tree['children'])) {
$tree['children'] = array();
}
$tree['children'][] = buildTree(array_slice($data,$key));
}
else if($child['depth'] <= ($lastLevel)){
return $tree;
}
}
return $tree;
}

$tree = buildTree($subtree);

print_r($tree);

关于php - 节点链接树和数据由 PHP 在 json 文件中填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com