如何从 etrepat/baum laravel 包导出所需的 json 格式的 jstree

how to export jstree desired json formatted from etrepat/baum laravel package

我正在使用 jstree jQuery plugin 将类别显示为树视图。

并且在后端,我使用 etrepat/baum laravel 包来创建类别嵌套集。

etrepat/baum 包有一个名为 toHierarchy() 的方法,它 return 是一个表示查询树的嵌套集合。

returned 的格式如下:

    {  
   "7":{  
      "org_level_id":7,
      "parent_id":5,
      "lft":7,
      "rgt":12,
      "depth":0,
      "name":"Computer",
      "created_at":"2015-11-02 00:45:01",
      "updated_at":"2015-11-02 00:45:01",
      "children":[  
         {  
            "org_level_id":14,
            "parent_id":7,
            "lft":8,
            "rgt":9,
            "depth":1,
            "name":"hard",
            "created_at":"2015-11-02 00:45:01",
            "updated_at":"2015-11-02 00:45:01",
            "children":[  

            ]
         },
         {  
            "org_level_id":13,
            "parent_id":7,
            "lft":10,
            "rgt":11,
            "depth":1,
            "name":" RAM",
            "created_at":"2015-11-02 00:45:01",
            "updated_at":"2015-11-02 00:45:01",
            "children":[  

            ]
         }
      ]
   },
   "9":{  
      "org_level_id":9,
      "parent_id":2,
      "lft":20,
      "rgt":23,
      "depth":0,
      "name":"search engines",
      "created_at":"2015-11-02 00:45:01",
      "updated_at":"2015-11-02 00:45:01",
      "children":[  
         {  
            "org_level_id":18,
            "parent_id":9,
            "lft":21,
            "rgt":22,
            "depth":1,
            "name":"Google",
            "created_at":"2015-11-02 00:45:01",
            "updated_at":"2015-11-02 00:45:01",
            "children":[  

            ]
         }
      ]
   },
   "17":{  
      "org_level_id":17,
      "parent_id":10,
      "lft":25,
      "rgt":26,
      "depth":0,
      "name":"Download",
      "created_at":"2015-11-02 00:45:01",
      "updated_at":"2015-11-02 00:45:01",
      "children":[  

      ]
   }
}

而另一方面,JStree 插件 需要一种 json 格式,比如从中创建树视图:

[
   'Simple root node',
   {
     'text' : 'Root node 2',
     'state' : {
       'opened' : true,
       'selected' : true
     },
     'children' : [
       { 'text' : 'Child 1' },
       'Child 2'
     ]
  }
]

如何将 etrepat/baum 的 return 格式转换为需要 jstree 的适当格式?

您可以在客户端或服务器端执行此操作。这是一个在服务器端执行的简单函数:

// $tree is the result of the toHierarchy assuming it is a JSON string
// if it is not - skip this json_decode step
$tree = json_decode($tree, true);

function parse($data) {
  $temp = [];
  foreach ($data as $id => $v) {
    unset($v['parent_id']);
    $v['id'] = $id;
    $v['text'] = $v['name'];
    if (count($v['children'])) {
      $v['children'] = parse($v['children']);
    }
    $temp[] = $v;
  }
  return $temp;
}

$tree = json_encode(parse($tree));
// now tree contains data that jstree will happily work with

生成的 JSON 对象将与 jstree 完美配合。您当然可以使用 unset 删除不需要的属性,以最大程度地减少数据量。

此致,
伊万