树状的分类算法(递归)
电脑办公 (电脑整机(笔记本, 平板电脑, 超极本), 外设产品)
数据格式:
Array(‘cat_id’=>’45’, ‘cat_name’=>’电脑办公’, ‘parent_id’=>’0’, ‘children’=>
Array(
Array(‘cat_id’=>’8’, ‘cat_name’=>’电脑整机’, ‘parent_id’=>’45’, ‘children’=>
Array(
Array(‘cat_id’=>’18’, ‘cat_name’=>’平板电脑’, ‘parent_id’=>’8’, ‘children’=>array())
Array(‘cat_id’=>’65’, ‘cat_name’=>’笔记本’, ‘parent_id’=>’8’, ‘children’=>array())
Array(‘cat_id’=>’71’, ‘cat_name’=>’超极本’, ‘parent_id’=>’8’, ‘children’=>array())
)
Array(‘cat_id’=>’11’, ‘cat_name’=>’外设产品’, ‘parent_id’=>’45’, ‘children’=>array())
)
)
<?php
public function getNextedList($p_id=0){
//获得所有的列表
$list=$this->getList();
//制作嵌套的数据,递归查找
return $this->getNexted($list,$p_id);
}
public function getNexted($list,$p_id){
$children=array();
foreach($list as $row){
if($row['parent_id']==$p_id){
$row['children']=$this->getNexted($list,$row['cat_id']);
$children[]=$row;
}
}
return $children;
}
?>