Php 变换对象平面数组介绍树
我有一个平面的对象数组,如下所示:Php 变换对象平面数组介绍树,php,arrays,parsing,tree,Php,Arrays,Parsing,Tree,我有一个平面的对象数组,如下所示: [ { id: "a", parent-id: "" }, { id: "b", parent-id: "a" }, { id: "c", parent-id: "b" }, { id: "d", parent-id: "" }, ... ] 我想将这个平面数组解析为一个树结构,其中具有父ID的对象作为其父对象的子元素插入,如下所示: [ { id
[
{
id: "a",
parent-id: ""
},
{
id: "b",
parent-id: "a"
},
{
id: "c",
parent-id: "b"
},
{
id: "d",
parent-id: ""
},
...
]
我想将这个平面数组解析为一个树结构,其中具有父ID的对象作为其父对象的子元素插入,如下所示:
[
{
id: "a",
parent-id: "",
children: [
{
id: "b",
parent-id: "a",
children: [
{
id: "c",
parent-id: "b"
}
]
}
]
},
{
id: "d",
parent-id: ""
},
...
]
转换发生在客户端还是服务器上并不重要,所以我的选项是PHP或JS。最简单的方法是什么?在PHP中,您可以尝试:
$foo = // your flat array of associative arrays
// add the top level nodes to an array
$result = array();
foreach ($foo as $node) {
if ($node['parent-id'] === '') {
$node['children'] = array();
array_push($result, $node);
}
}
// recursively iterate this array adding the children
addChildrenToArray($result, $foo);
function addChildrenToArray(&$array, $children) {
$parent_i = 0;
$child_i = 0;
foreach ($array as $parent_node) {
foreach ($children as $child_node) {
if ($child_node['parent-id'] == $parent_node['id']) {
$child_node['children'] = array();
array_push($array[$parent_i]['children'], $child_node);
addChildrenToArray($array[$parent_i]['children'], $children);
$child_i++;
}
}
$parent_i++;
}
}
语言在这里并不重要,因为代码几乎是sameWell,这看起来很简单,您必须遍历数组并逐个放置对象。我真的看不出这里有什么问题。。。