public function tree()
{
//這個表示那拿到的數(shù)據(jù)庫里面的內(nèi)容
$product=$this->order('catorder','asc')->select();
return $this->getTree($product);
}
//無限極遞歸
public function getTree($data,$pid=0,$level=0){
static $arr=array();
foreach($data as $key=>$value){
if($value['pid'] == $pid){
$value['level']=$level; //用來作為在模版進(jìn)行層級的區(qū)分
$arr[] = $value; //把內(nèi)容存進(jìn)去
$this->getTree($data,$value['id'],$level+1); //回調(diào)進(jìn)行無線遞歸
}
}
return $arr;
}
function recursionTree($arr,$pid)
{
$list = array();
foreach($arr as $val){
if($val['pid'] == $pid){
$tmp = recursionTree($arr,$val['id']);
if($tmp){
$val['son'] = $tmp;
}
$list[] = $val;
}
}
return $list;
}
$arr = [
['id'=>1,'pid'=>0,'name'=>'1-1'],
['id'=>2,'pid'=>1,'name'=>'1-1-2'],
['id'=>3,'pid'=>2,'name'=>'1-1-2-3'],
['id'=>4,'pid'=>0,'name'=>'1-4'],
['id'=>5,'pid'=>4,'name'=>'1-4-5'],
['id'=>6,'pid'=>0,'name'=>'1-6'],
];
$tmp = recursionTree($arr,0);
print_r($tmp);
//輸出
Array
(
[0] => Array
(
[id] => 1
[pid] => 0
[name] => 1-1
[son] => Array
(
[0] => Array
(
[id] => 2
[pid] => 1
[name] => 1-1-2
[son] => Array
(
[0] => Array
(
[id] => 3
[pid] => 2
[name] => 1-1-2-3
)
)
)
)
)
[1] => Array
(
[id] => 4
[pid] => 0
[name] => 1-4
[son] => Array
(
[0] => Array
(
[id] => 5
[pid] => 4
[name] => 1-4-5
)
)
)
[2] => Array
(
[id] => 6
[pid] => 0
[name] => 1-6
)
)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者