【问题标题】:Node link Tree and data populate by PHP in json file节点链接树和数据由 PHP 在 json 文件中填充
【发布时间】: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);

非常感谢您的帮助!

【问题讨论】:

    标签: php json algorithm tree


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 2019-08-14
      相关资源
      最近更新 更多