一、根据父节点ID循环遍历其下所有子节点
/** * @name 根据id递归某个父类节点下的所有分类节点 * @author tbj * @date 2015-12-19 */ public function traverseNodeClass($id) { $classDataArr = array(); $result = $this->_model->find() ->where(['parent_id'=>$id, 'deleted'=>0]) ->orderBy(['template_class_sort'=>SORT_ASC]) ->asArray() ->all(); if(!empty($result)) { foreach($result as $Key => $data) { $data['children'] = $this->traverseNodeClass($data['id']); $data['state'] = 'closed'; $classDataArr[] = $data; } } return $classDataArr; }
二、PHP无限极分类生成树方法
function generateTree($items){ $tree = array(); foreach($items as $item){ if(isset($items[$item['pid']])){ $items[$item['pid']]['son'][] = &$items[$item['id']]; }else{ $tree[] = &$items[$item['id']]; } } return $tree; } $items = array( 1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'), 2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'), 3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'), 4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'), 5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'), ); print_r(generateTree($items));
展示效果如下:
Array ( [0] => Array ( [id] => 1 [pid] => 0 [name] => 安徽省 [son] => Array ( [0] => Array ( [id] => 3 [pid] => 1 [name] => 合肥市 [son] => Array ( [0] => Array ( [id] => 4 [pid] => 3 [name] => 长丰县 ) ) ) [1] => Array ( [id] => 5 [pid] => 1 [name] => 安庆市 ) ) ) [1] => Array ( [id] => 2 [pid] => 0 [name] => 浙江省 ) )
备注:本文部分内容转载自http://www.phpddt.com/php/generateTree.html