How do you sort a tree stored using the nested set model?

前端 未结 8 660
不思量自难忘°
不思量自难忘° 2021-01-31 20:32

When I refer to nested set model I mean what is described here.

I need to build a new system for storing \"categories\" (I can\'t think of better word for it) in a user

相关标签:
8条回答
  • 2021-01-31 21:07

    You can sort thier when you render. I explained rendering here How to render all records from a nested set into a real html tree

    0 讨论(0)
  • 2021-01-31 21:07

    See my simple solution from method of my class. $this->table->order is Nette framework code to get data from DB.

    $tree = Array();
    $parents = Array();
    $nodes = $this->table->order('depth ASC, parent_id ASC, name ASC');
    $i = 0;
    $depth = 0;
    $parent_id = 0;
    
    foreach($nodes as $node) {
        if($depth < $node->depth || $parent_id < $node->parent_id) {
            $i = $parents["{$node->parent_id}"] + 1;
        }
        $tree[$i] = $node;
        $parents["{$node->id}"] = $i;
        $depth = $node->depth;
        $parent_id = $node->parent_id;
        $i += (($node->rgt - $node->lft - 1) / 2) + 1;
    }
    ksort($tree);
    
    0 讨论(0)
提交回复
热议问题