首先从数据库读数据,然后调用list_to_tree方法,再调用findchild方法,最后输出
$category = DB::name('CateGory'); $category_list = $category->select(); $data=$this->list_to_tree($category_list,'category_id','category_parent_id','children'); //调用下面的方法 $data=$this->findChild($data); header('Content-Type:APplication/json; charset=utf-8'); exit(json_encode($data,JSON_UNESCAPED_UNICODE)); // return $this->fetch('index'); $this->ajaxReturn($data, 'JSON');
下面是两个方法:
function findChild($arr){ static $tree=array(); foreach ($arr as $key=>$val){ $tree[]=$val; if (isset($val['_child'])){ $this->findChild($val['_child']); } } return $tree; } /** * 把返回的数据集转换成Tree * @access public * @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; }
添加新评论