찾다
php教程php手册实现PHP+Mysql无限分类的方法汇总

实现PHP+Mysql无限分类的方法汇总

Jun 13, 2016 am 09:13 AM
php+mysql분류성취하다기사방법제한 없는요약~의

实现PHP+Mysql无限分类的方法汇总

 这篇文章主要给大家汇总介绍了实现PHP+Mysql无限分类的2种方法,并对比分析了2种方法的优劣,需要的朋友可以参考下

 

 

无限分类是个老话题了,来看看PHP结合Mysql如何实现。

第一种方法

这种方法是很常见、很传统的一种,先看表结构

表:category
id int 主键,自增
name varchar 分类名称
pid int 父类id,默认0
顶级分类的 pid 默认就是0了。当我们想取出某个分类的子分类树的时候,基本思路就是递归,当然,出于效率问题不建议每次递归都查询数据库,通常的做法是先讲所有分类取出来,保存到PHP数组里,再进行处理,最后还可以将结果缓存起来以提高下次请求的效率。

先来构建一个原始数组,这个直接从数据库中拉出来就行:

 

代码如下:


$categories = array(
array('id'=>1,'name'=>'电脑','pid'=>0),
array('id'=>2,'name'=>'手机','pid'=>0),
array('id'=>3,'name'=>'笔记本','pid'=>1),
array('id'=>4,'name'=>'台式机','pid'=>1),
array('id'=>5,'name'=>'智能机','pid'=>2),
array('id'=>6,'name'=>'功能机','pid'=>2),
array('id'=>7,'name'=>'超级本','pid'=>3),
array('id'=>8,'name'=>'游戏本','pid'=>3),
);

 

目标是将它转化为下面这种结构

电脑
笔记本
超级本
游戏本
台式机
手机
智能机
功能机
用数组来表示的话,可以增加一个 children 键来存储它的子分类:

 

代码如下:


array(
//1对应id,方便直接读取
1 => array(
'id'=>1,
'name'=>'电脑',
'pid'=>0,
children=>array(
&array(
'id'=>3,
'name'=>'笔记本',
'pid'=>1,
'children'=>array(
//此处省略
)
),
&array(
'id'=>4,
'name'=>'台式机',
'pid'=>1,
'children'=>array(
//此处省略
)
),
)
),
//其他分类省略
)

 

处理过程:

 

代码如下:


$tree = array();
//第一步,将分类id作为数组key,并创建children单元
foreach($categories as $category){
$tree[$category['id']] = $category;
$tree[$category['id']]['children'] = array();
}
//第二部,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。
foreach ($tree as $k=>$item) {
if ($item['pid'] != 0) {
$tree[$item['pid']]['children'][] = &$tree[$k];
}
}
print_r($tree);

 

打印结果如下:

 

代码如下:


Array
(
[1] => Array
(
[id] => 1
[name] => 电脑
[pid] => 0
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => 笔记本
[pid] => 1
[children] => Array
(
[0] => Array
(
[id] => 7
[name] => 超级本
[pid] => 3
[children] => Array
(
)
)
[1] => Array
(
[id] => 8
[name] => 游戏本
[pid] => 3
[children] => Array
(
)
)
)
)
[1] => Array
(
[id] => 4
[name] => 台式机
[pid] => 1
[children] => Array
(
)
)
)
)
[2] => Array
(
[id] => 2
[name] => 手机
[pid] => 0
[children] => Array
(
[0] => Array
(
[id] => 5
[name] => 智能机
[pid] => 2
[children] => Array
(
)
)
[1] => Array
(
[id] => 6
[name] => 功能机
[pid] => 2
[children] => Array
(
)
)
)
)
[3] => Array
(
[id] => 3
[name] => 笔记本
[pid] => 1
[children] => Array
(
[0] => Array
(
[id] => 7
[name] => 超级本
[pid] => 3
[children] => Array
(
)
)
[1] => Array
(
[id] => 8
[name] => 游戏本
[pid] => 3
[children] => Array
(
)
)
)
)
[4] => Array
(
[id] => 4
[name] => 台式机
[pid] => 1
[children] => Array
(
)
)
[5] => Array
(
[id] => 5
[name] => 智能机
[pid] => 2
[children] => Array
(
)
)
[6] => Array
(
[id] => 6
[name] => 功能机
[pid] => 2
[children] => Array
(
)
)
[7] => Array
(
[id] => 7
[name] => 超级本
[pid] => 3
[children] => Array
(
)
)
[8] => Array
(
[id] => 8
[name] => 游戏本
[pid] => 3
[children] => Array
(
)
)
)

 

优点:关系清楚,修改上下级关系简单。

缺点:使用PHP处理,如果分类数量庞大,效率也会降低。

第二种方法

这种方法是在表字段中增加一个path字段:

表:category
id int 主键,自增
name varchar 分类名称
pid int 父类id,默认0
path varchar 路径
示例数据:

id name pid path
1 电脑 0 0
2 手机 0 0
3 笔记本 1 0-1
4 超级本 3 0-1-3
5 游戏本 3 0-1-3
path字段记录了从根分类到上一级父类的路径,用id+'-'表示。

这种方式,假设我们要查询电脑下的所有后代分类,只需要一条sql语句:

select id,name,path from category where path like (select concat(path,'-',id,'%') as path from category where id=1);
结果:

+----+-----------+-------+
| id | name | path |
+----+-----------+-------+
| 3 | 笔记本 | 0-1 |
| 4 | 超级本 | 0-1-3 |
| 5 | 游戏本 | 0-1-3 |
+----+-----------+-------+
这种方式也被很多人所采纳,我总结了下:

优点:查询容易,效率高,path字段可以加索引。

缺点:更新节点关系麻烦,需要更新所有后辈的path字段。

以上就是本文的全部内容了,两种方式,你喜欢哪种?希望大家能够喜欢。

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기