我想从从数据库获得的一维数组创建一个层次数组。语言是PHP。
在下面提到的示例中,键 id -3 表示它是根节点。
输入数据:
Array
(
[-2] => Array
(
[data] => A-2
[attr] => Array
(
[id] => -2
[parent_id] => -3
[title] => A-2
)
[state] => open
}
[-1] => Array
(
[data] => A-1
[attr] => Array
(
[id] => -1
[parent_id] => -2
[title] => A-1
)
[state] => open
}
[0] => Array
(
[data] => A0
[attr] => Array
(
[id] => 0
[parent_id] => -1
[title] => A0
)
[state] => open
}
[1] => Array
(
[data] => A1
[attr] => Array
(
[id] => 1
[parent_id] => -1
[title] => A1
)
[state] => open
}
[2] => Array
(
[data] => A2
[attr] => Array
(
[id] => 2
[parent_id] => -1
[title] => A2
)
[state] => open
}
[3] => Array
(
[data] => A3
[attr] => Array
(
[id] => 3
[parent_id] => 2
[title] => A3
)
[state] => open
}
[4] => Array
(
[data] => A4
[attr] => Array
(
[id] => 4
[parent_id] => 2
[title] => A4
)
[state] => open
}
[5] => Array
(
[data] => A5
[attr] => Array
(
[id] => 5
[parent_id] => -2
[title] => A5
)
[state] => open
}
}
输出预期数据:
Array
(
[-2] => Array
(
[data] => A-2
[attr] => Array
(
[id] => -2
[parent_id] => -3
[title] => A-2
)
[state] => open
[children] => Array
(
[-1] => Array
(
[data] => A-1
[attr] => Array
(
[id] => -1
[parent_id] => -2
[title] => A-1
)
[state] => open
[children] => Array
(
[0] => Array
(
[data] => A0
[attr] => Array
(
[id] => 0
[parent_id] => -1
[title] => A0
)
[state] => open
}
[1] => Array
(
[data] => A1
[attr] => Array
(
[id] => 1
[parent_id] => -1
[title] => A1
)
[state] => open
}
[2] => Array
(
[data] => A2
[attr] => Array
(
[id] => 2
[parent_id] => -1
[title] => A2
)
[state] => open
[children] => Array
(
[3] => Array
(
[data] => A3
[attr] => Array
(
[id] => 3
[parent_id] => 2
[title] => A3
)
[state] => open
}
[4] => Array
(
[data] => A4
[attr] => Array
(
[id] => 4
[parent_id] => 2
[title] => A4
)
[state] => open
}
)
)
)
)
[5] => Array
(
[data] => A5
[attr] => Array
(
[id] => 5
[parent_id] => -2
[title] => A5
)
[state] => open
)
)
)
)