Home > Article > Backend Development > PHP tree structure operation code (1/4)_PHP tutorial
Tree structure is used by many program members. The above tree structure operation class solves this problem very well.
/php tutorial tree structure operation code
/***************************************************** ***********
* Tree structure operation class (ideal if it can be written as a stored procedure)
*
* ************* **************************************************/
class treenode {
var $f_id = 'id';
var $f_pid = 'pid';
var $f_lft = 'lft';
var $f_rgt = 'rgt';
var $f_s = 'sequence';
var $f_level = 'lev';
var $f_child_num = 'child_num';
var $table;
var $db;
/**
* Constructor
* @param string $table table name
* @param object $dbhanle adodb database tutorial operation handle
*/
function treenode($table, $dbhandle) {
$this->db = $dbhandle;
$this->table = $table;
//$this->db->debug = true;
}
/**
* Add child node
* @param array $data Node data
* @return bool
*/
function addchild($data){
$pid = $data[$this->f_pid];
$sql = "select max({$this->f_s}) from {$this->table} where {$this->f_pid}=$pid";
$data[$this->f_s] = $this->db->getone($sql) + 1;//得到待插入节点的序号
$sql = "select * from {$this->table} where {$this->f_id} = -1";
$rs = $this->db->execute($sql);
$sql = $this->db->getinsertsql($rs, $data);
$this->db->execute($sql); //插入节点数据
if(!$this->db->affected_rows()){
return false;
}
$this->buildtree(1,1); //重建节点左右值
$this->updatelevel(1); //生成节点级数值
return true;
}
/**
* Modify node data
* @param int $id Node id number
* @param array $data Node data
* @return bool
*/1 2 3 4