1)无限级分类处理
<?php // 准备分类原始数据 $cate_arr = [ ['id'=>1,'name'=>'电脑','pid'=>0], ['id'=>2,'name'=>'手机','pid'=>0], ['id'=>3,'name'=>'戴尔','pid'=>1], ['id'=>4,'name'=>'联想','pid'=>1], ['id'=>5,'name'=>'苹果','pid'=>2], ['id'=>6,'name'=>'华为','pid'=>2], ['id'=>7,'name'=>'戴尔XPS','pid'=>3], ['id'=>8,'name'=>'苹果12','pid'=>5] ]; // 递归处理无限级分类 function getTree ($cate_arr = [] , $pid = 0 , $level = 0) { static $cate_tree_arr = []; foreach ($cate_arr as $key=>$value) { if ($value['pid'] == $pid) { $value['level'] = $level; $cate_tree_arr[] = $value; getTree($cate_arr,$value['id'],$level+1); } } return $cate_tree_arr; } // 显示无限级分类菜单 $cate_tree_arr = getTree($cate_arr); foreach ($cate_tree_arr as $key=>$value) { echo str_repeat("|----",$value['level']).$value['name'].'<br>'; }
2)根据指定分类项查找其父级分类
<?php // 准备分类原始数据 $cate_arr = [ ['id'=>1,'name'=>'电脑','pid'=>0], ['id'=>2,'name'=>'手机','pid'=>0], ['id'=>3,'name'=>'戴尔','pid'=>1], ['id'=>4,'name'=>'联想','pid'=>1], ['id'=>5,'name'=>'苹果','pid'=>2], ['id'=>6,'name'=>'华为','pid'=>2], ['id'=>7,'name'=>'戴尔XPS','pid'=>3], ['id'=>8,'name'=>'苹果12','pid'=>5] ]; // 查找指定菜单记录的父级分类 function getDeepPath ($cate_arr = [] , $current_cate_arr = []) { static $cate_deep_cate_arr = []; if (empty($cate_deep_cate_arr)) { $cate_deep_cate_arr[] = $current_cate_arr; } foreach ($cate_arr as $key=>$value) { if ($current_cate_arr['pid'] == $value['id']) { $cate_deep_cate_arr[] = $value; getDeepPath($cate_arr,$value); } } return $cate_deep_cate_arr; } // 显示父级分类层次 $cate_deep_cate_arr = getDeepPath($cate_arr,$cate_arr[7]); krsort($cate_deep_cate_arr); foreach ($cate_deep_cate_arr as $key=>$value) { echo ' -> '.$value['name']; }
3)根据指定分类查找其子级分类
<?php // 准备分类原始数据 $cate_arr = [ ['id'=>1,'name'=>'电脑','pid'=>0], ['id'=>2,'name'=>'手机','pid'=>0], ['id'=>3,'name'=>'戴尔','pid'=>1], ['id'=>4,'name'=>'联想','pid'=>1], ['id'=>5,'name'=>'苹果','pid'=>2], ['id'=>6,'name'=>'华为','pid'=>2], ['id'=>7,'name'=>'戴尔XPS','pid'=>3], ['id'=>8,'name'=>'苹果4','pid'=>5], ['id'=>9,'name'=>'苹果6','pid'=>5], ['id'=>10,'name'=>'苹果12','pid'=>5] ]; // 递归处理无限级分类 function getTree ($cate_arr = [] , $pid = 0 , $level = 0) { static $cate_tree_arr = []; foreach ($cate_arr as $key=>$value) { if ($value['pid'] == $pid) { $value['level'] = $level; $cate_tree_arr[] = $value; getTree($cate_arr,$value['id'],$level+1); } } return $cate_tree_arr; } // 显示无限级分类菜单(注意:这里在传参时直接指定想要查询的编号作为pid即可) $cate_tree_arr = getTree($cate_arr,2); foreach ($cate_tree_arr as $key=>$value) { echo str_repeat("|----",$value['level']).$value['name'].'<br>'; }