如何对SELECT语句的记录进行排序,使它们代表有效的树?
我的所有尝试都显示子节点嵌套在错误的父节点下.实现这种排序的最可靠方法是什么?
数据
ID Parent ID Title
--------------------------------------------
0 NULL Root
1 0 Node A
2 0 Node B
3 1 Sub-Node C
4 1 Sub-Node D
5 3 Sub-Node E
Run Code Online (Sandbox Code Playgroud)
产量
ID Parent ID Title
--------------------------------------------
0 NULL Root
1 0 Node A
3 1 Sub-Node C
5 3 Sub-Node E
4 1 Sub-Node D
2 0 Node B
Run Code Online (Sandbox Code Playgroud)
数据可视化
Root
Node A
Sub-Node C
Sub-Node E
Sub-Node D
Node B
Run Code Online (Sandbox Code Playgroud)
按照@Blindy的建议,我已经用PHP实现了这种方式.以下是两个似乎相对容易解决这个问题的功能.
protected function _sort_helper(&$input, &$output, $parent_id) {
foreach ($input as $key => $item)
if ($item->parent_id == $parent_id) {
$output[] = $item;
unset($input[$key]);
// Sort nested!!
$this->_sort_helper(&$input, &$output, $item->id);
}
}
protected function sort_items_into_tree($items) {
$tree = array();
$this->_sort_helper(&$items, &$tree, null);
return $tree;
}
Run Code Online (Sandbox Code Playgroud)
我很想知道是否有更简单的方法,但这似乎有效.