我找到了基于id< - > parent创建JSON的示例PHP代码,它看起来像:
<?php
$rows = array(
array('id' => 1, 'parent' => 0, 'name' => 'John Doe'),
array('id' => 2, 'parent' => 1, 'name' => 'Sally Smith'),
array('id' => 3, 'parent' => 2, 'name' => 'Mike Jones'),
array('id' => 4, 'parent' => 3, 'name' => 'Jason Williams'),
array('id' => 5, 'parent' => 4, 'name' => 'Sara Johnson'),
array('id' => 6, 'parent' => 1, 'name' => 'Dave Wilson'),
array('id' => 7, 'parent' => 2, 'name' => 'Amy Martin'),
);
// create an index on id
$index = array();
foreach($rows as $row){
$row['data'] = (object) [];
$index[$row['id']] = $row;
}
// build the tree
foreach($index as $id => &$row){
if ($id === 0) continue;
$parent = $row['parent'];
$index[$parent]['children'][] = &$row;
}
unset($row);
// obtain root node
$index = $index[0]['children'][0];
// output json
header('Content-Type: application/json');
echo json_encode($index, JSON_PRETTY_PRINT);
它工作正常,但如何显示特定ID的所有子记录?例如,我需要父2的所有成员,所以我尝试:
$index = $index[2]['children'][0];
它只显示3条记录,它应显示4条记录(Amy Martin缺失)。 谢谢。
答案 0 :(得分:0)
这是因为您正在尝试获取0
索引,因此仅显示第一层次结构。要访问所有子项,请从数据中删除[0]
应该是:
$index = $index[2]['children'];
答案 1 :(得分:0)
你只得到3条记录,因为你的“孩子”嵌套在不同的级别上(第4级是在不同的级别上
Array
(
[0] => Array
(
[id] => 3
[parent] => 2
[name] => Mike Jones
...
[children] => Array
(
[0] => Array
(
[id] => 4
[parent] => 3
[name] => Jason Williams
[children] => Array
(
[0] => Array
(
[id] => 5
[parent] => 4
[name] => Sara Johnson
...
)
)
)
)
)
[1] => Array
(
[id] => 7
[parent] => 2
[name] => Amy Martin
...
)
)
为了让所有的孩子都需要遍历并展平你的阵列。这可以使用interator完成。 完整代码示例:
<?php
$rows = array(
array('id' => 1, 'parent' => 0, 'name' => 'John Doe'),
array('id' => 2, 'parent' => 1, 'name' => 'Sally Smith'),
array('id' => 3, 'parent' => 2, 'name' => 'Mike Jones'),
array('id' => 4, 'parent' => 3, 'name' => 'Jason Williams'),
array('id' => 5, 'parent' => 4, 'name' => 'Sara Johnson'),
array('id' => 6, 'parent' => 1, 'name' => 'Dave Wilson'),
array('id' => 7, 'parent' => 2, 'name' => 'Amy Martin'),
);
// create an index on id
$index = array();
foreach($rows as $row){
$row['data'] = (object) [];
$index[$row['id']] = $row;
}
// build the tree
foreach($index as $id => &$row){
if ($id === 0) continue;
$parent = $row['parent'];
$index[$parent]['children'][] = &$row;
}
unset($row);
$array = $index[2]['children'];
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$data = array();
foreach ($iterator as $leafValue) {
if ( !$iterator -> hasChildren() ) {
if ($iterator->key() == 'id') {
$data[$leafValue]['id'] = $leafValue;
$id = $leafValue;
} else{
$data[$id][$iterator->key()] = $leafValue;
}
}
}
// output json
header('Content-Type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);
输出
{
"3": {
"id": 3,
"parent": 2,
"name": "Mike Jones"
},
"4": {
"id": 4,
"parent": 3,
"name": "Jason Williams"
},
"5": {
"id": 5,
"parent": 4,
"name": "Sara Johnson"
},
"7": {
"id": 7,
"parent": 2,
"name": "Amy Martin"
}
}