【发布时间】:2014-11-10 19:20:31
【问题描述】:
我使用 Nested set Model 来自这里: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);
非常感谢您的帮助!
【问题讨论】: