一道无限级分类题的 PHP 实现
今天有网友出了道题:
给出如下的父子结构(你可以用你所用语言的类似结构来描述,第一列是父,第二列是子),将其梳理成类似如图的层次父子结构。 origin = [('A112', 'A1122'), ('A', 'A1'), ('A', 'A2'), ('A1', 'A11'), ('A2', 'A21'), ('A2', 'A22'), ('A', 'A3'), ('A22', 'A221'), ('A11', 'A111'), ('A21', 'A211'), ('A11', 'A112'), ('A21', 'A212'), ('A11', 'A113'), ('A112', 'A1121'), ('A3', 'A31'), ('A31', 'A311'), ('A22', 'A222'), ('A31', 'A312'), ('A31', 'A313'), ('A311', 'A3111'), ('A312', 'A3121'), ('A3111', 'A31111')]
输出结果:
看了一下是无限级分类的原理,可以用递归来实现:
<?php $origin = [ ['A112', 'A1122'], ['A', 'A1'], ['A', 'A2'], ['A1', 'A11'], ['A2', 'A21'], ['A2', 'A22'], ['A', 'A3'], ['A22', 'A221'], ['A11', 'A111'], ['A21', 'A211'], ['A11', 'A112'], ['A21', 'A212'], ['A11', 'A113'], ['A112', 'A1121'], ['A3', 'A31'], ['A31', 'A311'], ['A22', 'A222'], ['A31', 'A312'], ['A31', 'A313'], ['A311', 'A3111'], ['A312', 'A3121'], ['A3111', 'A31111'] ]; // 根据父id找出子信息 function level($cate, $html = '-', $pid = '0', $level = 0) { $arr = array(); foreach($cate as $val) { if($val[0] == $pid) { $val['level'] = $level + 1; $val['html'] = str_repeat($html, $level); $arr[] = $val; $arr = array_merge($arr, level($cate, $html, $val[1], $level + 1)); } } return $arr; } // 构建顶级分类 $pids = []; $cids = []; foreach($origin as $val) { $pids[] = $val[0]; $cids[] = $val[1]; } $top = array_flip(array_diff($pids, $cids)); foreach($top as $key => $val) { $origin[] = ['0', $key]; } $res = level($origin, ' '); foreach($res as $k => $v) { echo $v['html'],$v[1],PHP_EOL; }
输出: