这里没有用递归查询,而是用得另一种处理方法
思路:获取到数据库的所有分类,通过代码,根据pid,返回分类树,
方法代码如下:
/**
* 分类树
*/
public static function getTree($data){
$items = [];
foreach ($data as $v){
//$v['category_id'] = $v['id'];这里需要自己做下转换,把id转换为category_id
$items[$v['category_id']] = $v;
//unset($v['id']);
}
//halt($items);
$tree = [];
foreach ($items as $id=>$item){
if(isset($items[$item['pid']])){
$items[$item['pid']['list']][] = &$items[$id];
}else{
$tree = &$items[$id];
}
}
return $tree;
}
数据库的数据为:
调用分类树之前:(我在查询返回后,就把id转换为category_id了,下面得category_id就是数据库对应得id)
^ array:11 [
0 => array:3 [
"category_id" => 11
"name" => "小米8"
"pid" => 2
]
1 => array:3 [
"category_id" => 10
"name" => "显示器"
"pid" => 6
]
2 => array:3 [
"category_id" => 9
"name" => "主板"
"pid" => 6
]
3 => array:3 [
"category_id" => 8
"name" => "联想"
"pid" => 5
]
4 => array:3 [
"category_id" => 7
"name" => "戴尔"
"pid" => 5
]
5 => array:3 [
"category_id" => 6
"name" => "华硕"
"pid" => 5
]
6 => array:3 [
"category_id" => 5
"name" => "电脑"
"pid" => 0
]
7 => array:3 [
"category_id" => 4
"name" => "小米10"
"pid" => 2
]
8 => array:3 [
"category_id" => 3
"name" => "红米"
"pid" => 2
]
9 => array:3 [
"category_id" => 2
"name" => "小米"
"pid" => 1
]
10 => array:3 [
"category_id" => 1
"name" => "手机"
"pid" => 0
]
]
调用分类树之后:
^ array:2 [
0 => array:4 [
"category_id" => 5
"name" => "电脑"
"pid" => 0
"list" => array:3 [
0 => array:3 [
"category_id" => 8
"name" => "联想"
"pid" => 5
]
1 => array:3 [
"category_id" => 7
"name" => "戴尔"
"pid" => 5
]
2 => array:4 [
"category_id" => 6
"name" => "华硕"
"pid" => 5
"list" => array:2 [
0 => array:3 [
"category_id" => 10
"name" => "显示器"
"pid" => 6
]
1 => array:3 [
"category_id" => 9
"name" => "主板"
"pid" => 6
]
]
]
]
]
1 => array:4 [
"category_id" => 1
"name" => "手机"
"pid" => 0
"list" => array:1 [
0 => array:4 [
"category_id" => 2
"name" => "小米"
"pid" => 1
"list" => array:3 [
0 => array:3 [
"category_id" => 11
"name" => "小米8"
"pid" => 2
]
1 => array:3 [
"category_id" => 4
"name" => "小米10"
"pid" => 2
]
2 => array:3 [
"category_id" => 3
"name" => "红米"
"pid" => 2
]
]
]
]
]
]
json格式展示效果:
这就完成了,根据pid分类的效果。