gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:35:17 25 4
gpt4 key购买 nike

我正在使用jstree jQuery plugin将类别显示为 TreeView 。

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

etrepat/baum 包有一个名为 toHierarchy() 的方法它返回代表查询树的嵌套集合。

返回的格式如下:

    {  
"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 格式,例如从中创建 TreeView :

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

如何将 etrepat/baum 的返回格式转换为 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 删除不需要的属性,以最大限度地减少数据量。

最诚挚的问候,
伊万

关于php - 如何从 etrepat/baum laravel 包导出 jstree 所需的 json 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36372969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com