<?php
class Tree{
private $OriginalList;
public $pk;//主鍵字段名
public $parentKey;//上級id字段名
public $childrenKey;//用來存儲子分類的數組key名
function __construct($pk="id",$parentKey="pid",$childrenKey="children"){
if(!empty($pk) && !empty($parentKey) && !empty($childrenKey)){
$this->pk=$pk;
$this->parentKey=$parentKey;
$this->childrenKey=$childrenKey;
}else{
return false;
}
}
//載入初始數組
function load($data){
if(is_array($data)){
$this->OriginalList=$data;
}
}
/**
* 生成嵌套格式的樹形數組
* array(..."children"=>array(..."children"=>array(...)))
*/
function DeepTree($root=0){
if(!$this->OriginalList){
return FALSE;
}
$OriginalList=$this->OriginalList;
$tree=array();//最終數組
$refer=array();//存儲主鍵與數組單元的引用關係
//遍歷
foreach($OriginalList as $k=>$v){
if(!isset($v[$this->pk]) || !isset($v[$this->parentKey]) || isset($v[$this->childrenKey])){
unset($OriginalList[$k]);
continue;
}
$refer[$v[$this->pk]]=&$OriginalList[$k];//爲每一個數組成員創建引用關係
}
//遍歷2
foreach($OriginalList as $k=>$v){
if($v[$this->parentKey]==$root){//根分類直接添加引用到tree中
$tree[]=&$OriginalList[$k];
}else{
if(isset($refer[$v[$this->parentKey]])){
$parent=&$refer[$v[$this->parentKey]];//獲取父分類的引用
$parent[$this->childrenKey][]=&$OriginalList[$k];//在父分類的children中再添加一個引用成員
}
}
}
return $tree;
}
}
$data=array(
0 => array("id"=>1,"pid"=>0),
1 => array("id"=>2,"pid"=>0),
2 => array("id"=>3,"pid"=>1),
3 => array("id"=>4,"pid"=>3),
4 => array("id"=>5,"pid"=>2),
);
var_dump($data);
$tree=new Tree("id","pid","children");
$tree->load($data);
$treelist=$tree->DeepTree();//全部分類樹結構
var_export($treelist);//查看結果
$subtree=$tree->DeepTree(1);//獲取id爲1下面的子樹
var_export($subtree);
?>php
轉自http://www.thinkphp.cn/topic/7487.htmlhtml