<?php
/**
* 由一个带fid的数组生成一个带children的树形数组
* 专为EasyUI的Tree的json格式设计
* @author ljb
*
*/
class BuildTreeArray
{
private $idKey = 'id'; //主键的键名
private $fidKey = 'fid'; //父ID的键名
private $root = 0; //最顶层fid
private $data = array(); //源数据
private $treeArray = array(); //属性数组
function __construct($data,$idKey,$fidKey,$root) {
if($idKey) $this->idKey = $idKey;
if($fidKey) $this->fidKey = $fidKey;
if($root) $this->root = $root;
if($data) {
$this->data = $data;
$this->getChildren($this->root);
}
}
/**
* 获得一个带children的树形数组
* @return multitype:
*/
public function getTreeArray()
{
//去掉键名
return array_values($this->treeArray);
}
/**
* @param int $root 父id值
* @return null or array
*/
private function getChildren($root)
{
foreach ($this->data as &$node){
if($root == $node[$this->fidKey]){
$node['children'] = $this->getChildren($node[$this->idKey]);
$children[] = $node;
}
//只要一级节点
if($this->root == $node[$this->fidKey]){
$this->treeArray[$node[$this->idKey]] = $node;
}
}
return $children;
}
}
?>
Array
(
[0] => Array
(
[id] => 1
[fid] => 0
[text] => 系统设置
[nodeUrl] => Admin
[children] => Array
(
[0] => Array
(
[id] => 2
[fid] => 1
[text] => 系统角色管理
[nodeUrl] => Admin&m=Sys&a=manageRole
[children] =>
)
[1] => Array
(
[id] => 3
[fid] => 1
[text] => 系统菜单管理
[nodeUrl] => Admin&m=Sys&a=manageNode
[children] =>
)
[2] => Array
(
[id] => 7
[fid] => 1
[text] => 用户管理
[nodeUrl] => Admin&m=Sys&a=manageUser
[children] =>
)
)
)
[1] => Array
(
[id] => 4
[fid] => 0
[text] => 笔记本
[nodeUrl] => Admin
[children] => Array
(
[0] => Array
(
[id] => 5
[fid] => 4
[text] => 添加笔记
[nodeUrl] => Admin&m=LjbNote&a=saveNote
[children] =>
)
[1] => Array
(
[id] => 6
[fid] => 4
[text] => 笔记列表
[nodeUrl] => Admin&m=LjbNote
[children] =>
)
[2] => Array
(
[id] => 8
[fid] => 4
[text] => 管理分类
[nodeUrl] => Admin&m=LjbNote&a=manageType
[children] =>
)
)
)
)
//使用方法
$data = doSql('SELECT nodeID id,fid,nodeName text FROM mytable');
$bta = new BuildTreeArray($data,'id','fid',0);
$data = $bta->getTreeArray();
echo json_encode($data);