<?php /** * 递归无限级分类【先序遍历算】,获取任意节点下所有子孩子 * @param array $arrCate 待排序的数组 * @param int $parent_id 父级节点 * @param int $level 层级数 * @return array $arrTree 排序后的数组 */ function getMenuTree($arrCat, $parent_id = 0, $level = 0) { static $arrTree = []; //使用static代替global if (empty($arrCat)) return []; $level++; foreach ($arrCat as $key => $value) { if ($value['parent_id'] == $parent_id) { $value['level'] = $level; $arrTree[] = $value; unset($arrCat[$key]); //注销当前节点数据,减少已无用的遍历 getMenuTree($arrCat, $value['id'], $level); } } return $arrTree; } /** * 把db返回的二维数组集转换成Tree * @param $list * @param string $pk * @param string $pid * @param string $child * @param int $root * @return array */ function listToTree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) { $tree = []; 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; } /** * 测试数据 */ $arrCate = array( //待排序数组 array('id' => 1, 'name' => '顶级栏目一', 'parent_id' => 0), array('id' => 2, 'name' => '顶级栏目二', 'parent_id' => 0), array('id' => 3, 'name' => '栏目三', 'parent_id' => 1), array('id' => 4, 'name' => '栏目四', 'parent_id' => 3), array('id' => 5, 'name' => '栏目五', 'parent_id' => 4), array('id' => 6, 'name' => '栏目六', 'parent_id' => 2), array('id' => 7, 'name' => '栏目七', 'parent_id' => 6), array('id' => 8, 'name' => '栏目八', 'parent_id' => 6), array('id' => 9, 'name' => '栏目九', 'parent_id' => 7), ); header('Content-type:text/html; charset=utf-8'); //设置utf-8编码 echo '树状结构展示子类'; echo '<pre>'; print_r(listToTree($arrCate, $pk = 'id', $pid = 'parent_id', $child = 'children', $root = 0)); echo '</pre>'; echo '展示所有子类'; echo '<pre>'; print_r(getMenuTree($arrCate, 2, 0)); echo '</pre>'; ?>
结果:
树状结构展示子类 Array ( [0] => Array ( [id] => 1 [name] => 顶级栏目一 [parent_id] => 0 [children] => Array ( [0] => Array ( [id] => 3 [name] => 栏目三 [parent_id] => 1 [children] => Array ( [0] => Array ( [id] => 4 [name] => 栏目四 [parent_id] => 3 [children] => Array ( [0] => Array ( [id] => 5 [name] => 栏目五 [parent_id] => 4 ) ) ) ) ) ) ) [1] => Array ( [id] => 2 [name] => 顶级栏目二 [parent_id] => 0 [children] => Array ( [0] => Array ( [id] => 6 [name] => 栏目六 [parent_id] => 2 [children] => Array ( [0] => Array ( [id] => 7 [name] => 栏目七 [parent_id] => 6 [children] => Array ( [0] => Array ( [id] => 9 [name] => 栏目九 [parent_id] => 7 ) ) ) [1] => Array ( [id] => 8 [name] => 栏目八 [parent_id] => 6 ) ) ) ) ) ) 展示所有子类 Array ( [0] => Array ( [id] => 6 [name] => 栏目六 [parent_id] => 2 [level] => 1 ) [1] => Array ( [id] => 7 [name] => 栏目七 [parent_id] => 6 [level] => 2 ) [2] => Array ( [id] => 9 [name] => 栏目九 [parent_id] => 7 [level] => 3 ) [3] => Array ( [id] => 8 [name] => 栏目八 [parent_id] => 6 [level] => 2 ) )