Two ways of thinking, recursive and non-recursive
Recursive
$arr = [ 1=>[' id ' =>1, ' pid ' =>0], 2=>[' id ' =>2, ' pid ' =>0], 3=>[' id ' =>3, ' pid ' = >1], 4=>[' id ' =>4, ' pid ' =>1], 5=>[' id ' =>5, ' pid ' =>0], 6=>[' id ' =>6, ' pid ' = >3], 7=>[' id ' =>7, ' pid ' =>6], 8=>[' id ' =>8, ' pid ' =>3], 9=>[' id ' =>9, ' pid ' = >4], 10=>[' id ' =>10, ' pid ' =>7], 11=>[' id ' =>11, ' pid ' =>7],];//sort array arr layer level Key Valfunction display_test ($arr, $level, $val) { if ($level ==0) { echo "top-level directory \ n"; } else{ Echo str_repeat (" , $level). $arr [$val] [' ID ']." \ n "; } $temp = Get ($arr, $val); foreach ($temp as $v) { display_test ($arr, $level +1, $v [' id ']);} } Gets all the next-level child nodes of the PID function get ($arr, $pid) { $res = []; foreach ($arr as $v) { if ($v [' pid ']== $pid) { $res [] = $v; } } return $res;} Display_test ($arr, 0,0);d ie;
Non-recursive left and right value method
Table structure
CREATE TABLE ' sys_department ' ( ' id ' int (one) not null auto_increment, ' name ' varchar () DEFAULT NULL COMMENT ' department name Called ', ' description ' varchar ($) Default null COMMENT ' description ', ' create_time ' int (one) default null COMMENT ' Add time ', ' left_value ' int (one) default null, ' right_value ' int (one) default null, PRIMARY KEY (' id ')) engine=innodb auto_increment=4 DEFAULT Charset=utf8 comment= ' departmental table '
Add new subordinates: Use things
Modify the right value $sql = "UPDATE {$this->table} SET right_value = right_value+2 WHERE right_value>=:right_value";//Modify the left value c8/> $sql = "UPDATE {$this->table} SET left_value = left_value+2 WHERE left_value>=:left_value";//Insert $sql = "Insert in to {$this->table} (Name,description,left_value,right_value,create_time) VALUES (: Name,:d Escription,:left_value, : Right_value,:create_time) ";
Delete node: use things
Delete $sql = "Delete from {$this->table} WHERE Left_value>=:left_value and Right_value<=:right_value";// Modify Lvalue $sql = "UPDATE {$this->table} SET left_value=left_value-{$offset} WHERE Left_value>:left_value";//Modify Right value $sql = "UPDATE {$this->table} SET right_value=right_value-{$offset} WHERE right_value>:right_value";
Gets all nodes that contain indentation
Public Function Display_tree ($id) { //Get node $model = $this->model->getbyid ($id); if (! $model) { return false; } $left = $model [' Left_value ']; $right = $model [' Right_value '];//gets the child nodes sorted by left_value $res = $this->getbyleftright ($left, $right); $temp = [];//loop to find the node in the progression of foreach ($res as $k = + $v) { if (count ($temp) >0) { // Check if we should move the node out of the stack while ($temp [count ($temp)-1] < $v [' Right_value ']) { array_pop ($temp)} } echo str_repeat ("*", Count ($temp)). $v [' name ']. " \ n "; $res [$k] [' level '] = count ($temp); $temp [] = $v [' Right_value ']; } Level first layer return $res; }
MySQL Infinite class classification