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

时间:2014-09-16 21:49:16

标签: php json algorithm tree

我使用此处的嵌套集模型http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/以及来自子树深度部分的查询。

我想将此图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);

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

当你到达非孩子时,你需要能够停止递归循环。通过返回到目前为止的结果。 此外,您不需要$ 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);