我正在使用 Stof 的 DoctrineExtension 包来检索我的树,现在我想将该树转换为一个数组(然后将其转换为 json)。
尽管 NestedTreeRepository->childrenHierarchy() 的格式不正确,但我想修改输出,因此只返回节点“title”属性和“id”属性,并将所有子节点放入“children”子数组中. 符合此格式 (JSON):
{
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
},
{
label: 'node2',
children: [
{ label: 'child3' }
]
}
}
我尝试遵循代码,这与 childrenHierarchy() 返回相同,但允许我修改查询。
$query = $em
->createQueryBuilder()
->select('node')
->from('MyBundle:Page', 'node')
->orderBy('node.root, node.lft', 'ASC')
->getQuery()
;
$nodes = $query->getArrayResult();
[Do magic here]
$tree = $pagerepo->buildTree($nodes);
是否可以将每个节点类型转换为仅包含以下属性的更简单的对象:
- ID
- 标题
- 其他一些用于定位的整数
如果我然后通过 json_encode() 运行它,我将拥有我需要的东西。
当然欢迎任何其他解决方案。