#### 1. 无限级分类数据 --- **本文章中的算法使用的都是以下数据** ```php $array = [ ['id' => 1, 'pid' => 0, 'name' => '河南省'], ['id' => 2, 'pid' => 0, 'name' => '山东省'], ['id' => 3, 'pid' => 0, 'name' => '四川省'], ['id' => 4, 'pid' => 1, 'name' => '郑州市'], ['id' => 5, 'pid' => 1, 'name' => '开封市'], ['id' => 6, 'pid' => 4, 'name' => '金水区'], ['id' => 7, 'pid' => 5, 'name' => '兰考县'], ]; ``` #### 2. 使用引用算法转为无限级分类树 --- ``` $data = getTree($data); ``` ```php /** * 数据格式转换 * 将数据转为无限级分类树 */ function getTree($arr) { $refer = []; $tree = []; foreach ($arr as $k => $v) { //创建主键的数组引用 $refer[$v['id']] = & $arr[$k]; } foreach ($arr as $k => $v) { //上级id $pid = $v['pid']; if ($pid == 0) { //顶级栏目 $tree[] = & $arr[$k]; } else { if (isset($refer[$pid])) { //如果存在上级栏目,则将当前栏目添加到上级栏目的子栏目中 $refer[$pid]['subcat'][] = & $arr[$k]; } } } return $tree; } ```