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


Node link Tree and data populate by PHP in json file

我从这里使用嵌套集模型: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(我不使用大小属性)

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

$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);