菜单

Implementation of accounting tree menu in ComboTree

2017年11月22日 - PHPer

Suppose the fields of the accounting data table in the database are: ID, code, name, islast. They are self increasing primary keys, subject codes, subject names, and whether they are final (“1” means last stage subjects).

Here, we use recursion to build the data needed by ComboTree in the model layer of Thinkphp, and the code and annotations are as follows:

 

Code is as follows

Namespace Home\Model;

Use Think\Model;

 

Class AccountModel extends Model{

 

(publicfunctiongetTreeList) {

$data = $this-> field (‘id, code, name, islast’) -&gt (select);

Foreach ($data as & $v) {/ / here to join the PID element, is used to identify parent ID

$len = strlen ($v[‘code’]);

If ($len = = 3) {/ / the assumption here is that the length of the 3 subjects encoding is one level, 5 for two subjects, 7 to three, and so on

$v[‘pid’] = 0;

}else{

$v[‘pid’] = substr ($v[‘code’], 0, $len-2);

}

}

Return$this-> createTree ($data); / / generated data structure required by ComboTree

}

  

/ recursively generated subtree

PrivatefunctioncreateSubTree ($data, $pid) {

($tree = array);

Foreach ($data as $k=> $v) {

If ($v[‘pid’] = = $pid) {

($newDate = array

‘id’=> $v[‘id’],

‘text’=> $v[‘name’],

‘state’=> ($v[‘islast’]! = 1)?’closed’:’open’

);

If ($v[‘islast’]! = 1) {/ / if not the final subject to call itself generating data

$subData = $this-> createSubTree ($data, $v[‘code’]);

If (! Empty ($subData)) {

$newDate[‘children’] = $subData;

}

}

Array_push ($tree, $newDate);

}

}

Return$tree;

}

  

/ / spanning tree, start from the level of accounting classification data to create the menu tree

PrivatefunctioncreateTree ($data) {

($ret = array);

Foreach ($data as $k => $v) {

If ($v[‘pid’] = = 0) {

$newDate = array (/ created to recognize the format for the ComboTree here, I have no better way, only this

‘id’=> $v[‘id’],

‘text’=> $v[‘name’],

‘state’=>’closed’

);

$subData = $this-> createSubTree ($data, $v[‘code’]);

If (! Empty ($subData)) {

$newDate[‘children’] = $subData;

}

$ret[] = $newDate;

}

}

Return$ret;

}

}

 

Similar to the above data (such as departments, regions, etc.) need to build a simple menu tree modify the code, basically can achieve similar functions.

发表评论

电子邮件地址不会被公开。