我在PHP中创建多维JSON对象时遇到了麻烦。
我的Postgresql数据库如下所示:
Id Name Parent
1 Active NULL
2 Passive NULL
3 Fixed 1
4 Dynamic 3
5 Taxes 2
6 Fair 2
...
父列与第一列中的Id链接
我想要完成的是:
[
{
"name": "Active",
"children": [
{
"name": "Fixed",
"children": [
{
"name": "Dynamic",
"children": NULL
}
]
}
]
},
{
"name": "Passive",
"children": [
{
"name": "Taxes",
"children": NULL
},
{
"name": "Fair",
"children": NULL
}
]
}
]
首先,我FETCH
使用
$result = fetchAll(PDO::FETCH_OBJ); // fetches every row in an object
我可以将此结果发送到前端(javascript)并将此数据转换为JSON,然后我发送列名称,我不认为这在安全方面是个好主意。
首先,我想制作JSON文件的顶级。在这个主题Object to array in PHP的帮助下,我设法将它们放在一起:
$mainArray = [];
foreach ($result as $value) {
if ($value['Parent'] === NULL) {
$object = new stdClass();
$object->name = $value['Name'];
$object->children = [];
$mainArray[] = $object;
}
}
这是我的结果:
[
{
name: "Actief",
children: [ ]
},
{
name: "Passief",
children: [ ]
}
]
但是我没有把孩子加到正确的父母那里。我似乎无法找到如何做到这一点。
我需要做这样的事情:
将Fixed
添加到Object
Object->Name
1 = Active
的{{1}}。
答案 0 :(得分:1)
这将完成这项工作。假设您的子数据不会出现在父数据之前。
$mainArray = [];
foreach ($result as $key=>$value) {
if ($value['Parent'] === NULL) {
$object = new stdClass();
$object->name = $value['Name'];
$mainArray[$value['Id']] = $object;
}else{
$childOBJ = new stdClass();
$childOBJ->name = $value['Name'];
$mainArray[$value['Parent']]->children[] = $childOBJ;
}
}
$finalArray = array_values($mainArray); // changes to indexed array for json purpose
更新:WITH RECURSION和refrence
function makeTree($result, $parentId=NULL){
$tree = [];
foreach ($result as $value) {
if($value['Parent'] == $parentId){
$object = new stdClass();
$object->name = $value['Name'];
$child = makeTree($result, $value['Id']);
if($child){
$object->children=$child;
}
$tree[] = $object;
}
}
return $tree;
}
$finalArray = makeTree($result);