第一种
public function getTree($data,$id=0,$lev=1,$iscache=true)
{
static $list = array();
//根据参数决定是否需要重置
if(!$iscache){
$list=array();
}
foreach ($data as $key => $value) {
if($value['parent_id']==$id){
$value['lev']=$lev;
$list[]=$value;
//使用递归的方式获取分类下的子分类
$this->getTree($data,$value['id'],$lev+1);
}
}
return $list;
}
第二种
/**
* 分类路径配置
* @param string $m ,$pid 数据表,父id
* @return null
* @author App <itholiday@126.com>
*/
function setPath($m, $pid)
{
$cate = $m;
$map['id'] = $pid;
$list = $cate->field('id,path')->where($map)->limit(1)->find();
$path = $list['path'] . '-' . $list['id'];
$lv = count(explode('-', $path));
return array('path' => $path, 'lv' => $lv);
}
/**
* SonCate配置
* @param string $m ,$pid 数据表,父id
* @return null
* @author App <itholiday@126.com>
*/
function setSoncate($m, $pid)
{
$cate = $m;
$map['pid'] = $pid;
$father = $cate->where('id=' . $pid)->limit(1)->find();
$son = $cate->field('id')->where($map)->select();
if ($son && $father) {
//存在子栏目
$arr = '';
foreach ($son as $k => $v) {
$arr = $arr . $v['id'] . ',';
}
$father['soncate'] = $arr;
$rf = $m->save($father);
if ($rf === FALSE) {
return FALSE;
} else {
return TRUE;
}
} elseif (!$son && $father) {
//子栏目为空
$father['soncate'] = '';
$rf = $m->save($father);
if ($rf === FALSE) {
return FALSE;
} else {
return TRUE;
}
} else {
//未知错误
return FALSE;
}
}
/**
* 获取分类
* @param string $m
* @return array
*/
function getCate($m, $where = '')
{
$cates = array();
$list = $m->where($where)->select();
foreach ($list as $k => $v) {
$cates[$v['id']] = $v['name'];
}
return $cates;
}
/**
* AppTree快速无限分类树
* @param string $m ,$pid 数据表,父id
* @return null
* @author App <itholiday@126.com>
*/
function appTree($pid, $field, $map, $order = 'sorts desc', $keyid = 'id', $keypid = 'pid', $tree = true, $keychild = '_child')
{
$sql = "select $field from ims_yq_haircircle_task_cate where $map order by $order";
$list = pdo_fetchall($sql);
if ($tree) {
$list = list_to_tree($list, $keyid, $keypid, $keychild, $root = $pid);//无限
} else {
$list = array();
$list = list_to_treelist($list, $keyid, $keypid, $root = $pid);//二维
}
return $list;
}
/**
* 把返回的数据集转换成Tree
* @param array $list 要转换的数据集
* @param string $pid parent标记字段
* @param string $level level标记字段
* @return array
*/
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
// 创建Tree
$tree = array();
if (is_array($list)) {
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] = &$list[$key];
}
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[] = &$list[$key];
} else {
if (isset($refer[$parentId])) {
$parent = &$refer[$parentId];
$parent[$child][] = &$list[$key];
}
}
}
}
return $tree;
}