【发布时间】:2012-06-29 16:17:13
【问题描述】:
可能重复:
Converting an array from one to multi-dimensional based on parent ID values
我正在使用 PHP。
我有以下包含关系数据(父子关系)的数组。
Array
(
[5273] => Array
(
[id] => 5273
[name] => John Doe
[parent] =>
)
[6032] => Array
(
[id] => 6032
[name] => Sally Smith
[parent] => 5273
)
[6034] => Array
(
[id] => 6034
[name] => Mike Jones
[parent] => 6032
)
[6035] => Array
(
[id] => 6035
[name] => Jason Williams
[parent] => 6034
)
[6036] => Array
(
[id] => 6036
[name] => Sara Johnson
[parent] => 5273
)
[6037] => Array
(
[id] => 6037
[name] => Dave Wilson
[parent] => 5273
)
[6038] => Array
(
[id] => 6038
[name] => Amy Martin
[parent] => 6037
)
)
我需要它是这种 JSON 格式:
{
"id":"5273",
"name":"John Doe",
"data":{
},
"children":[
{
"id":" Sally Smith",
"name":"6032",
"data":{
},
"children":[
{
"id":"6034",
"name":"Mike Jones",
"data":{
},
"children":[
{
"id":"6035",
"name":"Jason Williams",
"data":{
},
"children":[
{
"id":"node46",
"name":"4.6",
"data":{
},
"children":[
]
}
]
}
]
},
{
"id":"6036",
"name":"Sara Johnson",
"data":{
},
"children":[
]
},
{
"id":"6037",
"name":"Dave Wilson",
"data":{
},
"children":[
{
"id":"6038",
"name":"Amy Martin",
"data":{
},
"children":[
]
}
]
}
]
}
]
}
我知道我需要创建一个多维数组并通过 json_encode() 运行它。我还认为用于执行此操作的这种方法需要递归,因为现实世界的数据可能具有未知数量的级别。
我很乐意展示我的一些方法,但它们没有奏效。
谁能帮帮我?
我被要求分享我的工作。这是我尝试过的,但我没有得到那么接近我不知道它有多大帮助。
我制作了一个仅包含关系的数组。
foreach($array as $k => $v){
$relationships[$v['id']] = $v['parent'];
}
我认为(基于另一篇 SO 帖子)使用此关系数据创建了一个新的多维数组。如果我让它工作,我将努力添加正确的“儿童”标签等。
$childrenTable = array();
$data = array();
foreach ($relationships as $n => $p) {
//parent was not seen before, put on root
if (!array_key_exists($p, $childrenTable)) {
$childrenTable[$p] = array();
$data[$p] = &$childrenTable[$p];
}
//child was not seen before
if (!array_key_exists($n, $childrenTable)) {
$childrenTable[$n] = array();
}
//root node has a parent after all, relocate
if (array_key_exists($n, $data)) {
unset($data[$n]);
}
$childrenTable[$p][$n] = &$childrenTable[$n];
}
unset($childrenTable);
print_r($data);
【问题讨论】:
-
您发布的初始格式是一个多维数组。这不应该在 json 编码中工作吗?
-
Ben Roux,是的,这是一个多维数组,但生成该 JSON 的格式不正确。
-
你试过什么?发布你的代码你是如何准备数组的。
-
Sanjay,我在我的问题中添加了一些我的工作。我无法在 cmets 中获得正确的格式。我也尝试过do-while,但也失败了。
-
Yoshi,我回过头来记下所有以前的答案都是某些解决方案。我希望这有帮助。我以后会更好地跟上这一点。
标签: php json recursion multidimensional-array