PHP无限分类
顶级分类下面有子分类,子分类下面又有孙分类,子子孙孙无穷尽也。
怎么让这个分类功能支持无限个,说是无限,其实也是有限。算法可以无限,实际使用中总是有限,毕竟计算机的内存是有限的。
无限分类实现如下:
function tree_list($list,$p_id = 0,$p_field='p_id'){ //用于保存整理好的分类节点 $tree = []; // 循环所有分类 foreach ($list as $key => $value) { // 如果当前分类的父id等于要寻找的父id则写入$tree 数组,并寻找当前分类id下的所有子分类 if($p_id == $value[$p_field]) { $tree [$key] = $value; $tree [$key] ['children'] = tree_list($list,$value ['id'],$p_field); } } return $tree; } //假如这是数据库查出来的 $test_list=[ ['id'=>1,'p_id'=>0,'name'=>'分类1'], ['id'=>2,'p_id'=>0,'name'=>'分类1'],//顶级分类 ['id'=>3,'p_id'=>0,'name'=>'分类2'],//顶级分类 ['id'=>4,'p_id'=>0,'name'=>'分类3'],//顶级分类 ['id'=>5,'p_id'=>0,'name'=>'分类4'],//顶级分类 ['id'=>6,'p_id'=>0,'name'=>'分类5'],//顶级分类 ['id'=>7,'p_id'=>0,'name'=>'分类6'],//顶级分类 ['id'=>8,'p_id'=>0,'name'=>'分类7'],//顶级分类 ['id'=>9,'p_id'=>1,'name'=>'分类8(子)'],//子级分类 ['id'=>10,'p_id'=>9,'name'=>'分类9(孙)'],//孙级分类 ['id'=>11,'p_id'=>10,'name'=>'分类10(曾孙)'],//曾孙级分类 ]; $tree_list=tree_list($test_list,$p_id = 0,$p_field='p_id'); print_r($tree_list);
输出:
Array ( [0] => Array ( [id] => 1 [p_id] => 0 [name] => 分类1 [children] => Array ( [8] => Array ( [id] => 9 [p_id] => 1 [name] => 分类8(子) [children] => Array ( [9] => Array ( [id] => 10 [p_id] => 9 [name] => 分类9(孙) [children] => Array ( [10] => Array ( [id] => 11 [p_id] => 10 [name] => 分类10(曾孙) [children] => Array ( ) ) ) ) ) ) ) ) [1] => Array ( [id] => 2 [p_id] => 0 [name] => 分类1 [children] => Array ( ) ) [2] => Array ( [id] => 3 [p_id] => 0 [name] => 分类2 [children] => Array ( ) ) [3] => Array ( [id] => 4 [p_id] => 0 [name] => 分类3 [children] => Array ( ) ) [4] => Array ( [id] => 5 [p_id] => 0 [name] => 分类4 [children] => Array ( ) ) [5] => Array ( [id] => 6 [p_id] => 0 [name] => 分类5 [children] => Array ( ) ) [6] => Array ( [id] => 7 [p_id] => 0 [name] => 分类6 [children] => Array ( ) ) [7] => Array ( [id] => 8 [p_id] => 0 [name] => 分类7 [children] => Array ( ) ) )
//递归获取所有的子分类的ID
function get_all_child($array,$id){ $arr = array(); foreach($array as $v){ if($v['pid'] == $id){ $arr[] = $v['id']; $arr = array_merge($arr,get_all_child($array,$v['id'])); }; }; return $arr; }