实现PHP+Mysql无限分类的方法汇总,phpmysql
实现PHP+Mysql无限分类的方法汇总,phpmysql
无限分类是个老话题了,来看看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字段。
以上就是本文的全部内容了,两种方式,你喜欢哪种?希望大家能够喜欢。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

SQL statements can be created and executed based on runtime input by using Oracle's dynamic SQL. The steps include: preparing an empty string variable to store dynamically generated SQL statements. Use the EXECUTE IMMEDIATE or PREPARE statement to compile and execute dynamic SQL statements. Use bind variable to pass user input or other dynamic values to dynamic SQL. Use EXECUTE IMMEDIATE or EXECUTE to execute dynamic SQL statements.
