實現PHP+Mysql無限分類的方法匯總
Jun 13, 2016 am 09:13 AM實現PHP+Mysql無限分類的方法匯總
?這篇文章主要給大家匯總介紹了實現PHP+Mysql無限分類的2種方法,并對比分析了2種方法的優(yōu)劣,需要的朋友可以參考下
?
?
無限分類是個老話題了,來看看PHP結合Mysql如何實現。
第一種方法
這種方法是很常見、很傳統(tǒng)的一種,先看表結構
表: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,并創(chuàng)建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
(
)
)
)
?
優(yōu)點:關系清楚,修改上下級關系簡單。
缺點:使用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 |
+----+-----------+-------+
這種方式也被很多人所采納,我總結了下:
優(yōu)點:查詢容易,效率高,path字段可以加索引。
缺點:更新節(jié)點關系麻煩,需要更新所有后輩的path字段。
以上就是本文的全部內容了,兩種方式,你喜歡哪種?希望大家能夠喜歡。

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

1. How can you make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! 1. Activate basic rights and interests: original articles can earn profits by advertising, and videos must be original in horizontal screen mode to earn profits. 2. Activate the rights of 100 fans: if the number of fans reaches 100 fans or above, you can get profits from micro headlines, original Q&A creation and Q&A. 3. Insist on original works: Original works include articles, micro headlines, questions, etc., and are required to be more than 300 words. Please note that if illegally plagiarized works are published as original works, credit points will be deducted, and even any profits will be deducted. 4. Verticality: When writing articles in professional fields, you cannot write articles across fields at will. You will not get appropriate recommendations, you will not be able to achieve the professionalism and refinement of your work, and it will be difficult to attract fans and readers. 5. Activity: high activity,
