Infinite classification is an old topic , Let's see PHP combination Mysql How to achieve .
The first method
This method is very common 、 It's a very traditional one , First look at the structure of the watch
surface :category
id int Primary key , Self increasing
name varchar Category name
pid int Parent class id, Default 0
Top class pid The default is 0 了 . When we want to take out the subcategory tree of a certain classification , The basic idea is recursion , Of course , For the sake of efficiency, it is not recommended to query the database every time , The usual practice is to first talk about all the classifications and take them out , Save to PHP In the array , Reprocessing , Finally, the results can be cached to improve the efficiency of the next request .
Let's start by building a raw array , Just pull it out of the database :

$categories = array(
array('id'=>1,'name'=>' The computer ','pid'=>0),
array('id'=>2,'name'=>' mobile phone ','pid'=>0),
array('id'=>3,'name'=>' The notebook ','pid'=>1),
array('id'=>4,'name'=>' Desktop computer ','pid'=>1),
array('id'=>5,'name'=>' Intelligent machine ','pid'=>2),
array('id'=>6,'name'=>' Function machine ','pid'=>2),
array('id'=>7,'name'=>' Ultrabook ','pid'=>3),
array('id'=>8,'name'=>' Game book ','pid'=>3),
);
 

The goal is to transform it into the following structure
The computer
    The notebook
        Ultrabook
        Game book
    Desktop computer
mobile phone
    Intelligent machine
    Function machine
In terms of arrays , You can add one children Key to store its subcategories :

Treatment process :

        $tree = array ();
// First step , Classify id As an array key, And create children unit
foreach ( $categories as $category ) {
$tree [$category ['id']] = $category;
$tree [$category ['id']] ['children'] = array ();
} // Second parts , Use quotes , Add each category to the parent class children Array , Such a traversal can form a tree structure .
foreach ( $tree as $k => $item ) {
if ($item ['pid'] != 0) {
$tree [$item ['pid']] ['children'] [] = $tree [$k];
}
}
var_dump ( $tree );

  

 
Array
(
[1] => Array
(
[id] => 1
[name] => The computer
[pid] => 0
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => The notebook
[pid] => 1
[children] => Array
(
[0] => Array
(
[id] => 7
[name] => Ultrabook
[pid] => 3
[children] => Array
(
)
)
[1] => Array
(
[id] => 8
[name] => Game book
[pid] => 3
[children] => Array
(
)
)
)
)
[1] => Array
(
[id] => 4
[name] => Desktop computer
[pid] => 1
[children] => Array
(
)
)
)
)
[2] => Array
(
[id] => 2
[name] => mobile phone
[pid] => 0
[children] => Array
(
[0] => Array
(
[id] => 5
[name] => Intelligent machine
[pid] => 2
[children] => Array
(
)
)
[1] => Array
(
[id] => 6
[name] => Function machine
[pid] => 2
[children] => Array
(
)
)
)
)
[3] => Array
(
[id] => 3
[name] => The notebook
[pid] => 1
[children] => Array
(
[0] => Array
(
[id] => 7
[name] => Ultrabook
[pid] => 3
[children] => Array
(
)
)
[1] => Array
(
[id] => 8
[name] => Game book
[pid] => 3
[children] => Array
(
)
)
)
)
[4] => Array
(
[id] => 4
[name] => Desktop computer
[pid] => 1
[children] => Array
(
)
)
[5] => Array
(
[id] => 5
[name] => Intelligent machine
[pid] => 2
[children] => Array
(
)
)
[6] => Array
(
[id] => 6
[name] => Function machine
[pid] => 2
[children] => Array
(
)
)
[7] => Array
(
[id] => 7
[name] => Ultrabook
[pid] => 3
[children] => Array
(
)
)
[8] => Array
(
[id] => 8
[name] => Game book
[pid] => 3
[children] => Array
(
)
)
)

 

 

advantage : The relationship is clear , It's easy to modify the relationship between superior and subordinate .

shortcoming : Use PHP Handle , If the number of categories is huge , Efficiency will also be reduced .

The second method

This method is to add a path Field :

surface :category
id int Primary key , Self increasing
name varchar Category name
pid int Parent class id, Default 0
path varchar route
Example data :

id        name        pid        path
1         The computer         0          0
2         mobile phone         0          0
3         The notebook       1          0-1
4         Ultrabook       3          0-1-3
5         Game book       3          0-1-3
path Field records the path from the root class to the parent class , use id+'-' Express .

This way, , Let's say we want to look up all the offspring categories on the computer , Just one sql sentence :

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

+----+-----------+-------+
| id | name      | path  |
+----+-----------+-------+
| 3  | The notebook | 0-1   |
| 4  | Ultrabook | 0-1-3 |
| 5  | Game book | 0-1-3 |
+----+-----------+-------+
This approach has also been adopted by many people , I sum up :

advantage : Easy to query , Efficient ,path Fields can be indexed .

shortcoming : It's troublesome to update the node relationship , Need to update all the younger generation's path Field .

That's all of this , Two ways , What kind of... Do you like ? I hope you like it .

PHP+Mysql More related articles are summarized by infinite classification method

  1. MySql Infinite classification data structure -- Pre sort traversal tree algorithm

    MySql Infinite classification data structure -- Pre sort traversal tree algorithm Infinite classification is a very common application in our development , Like the forum section ,CMS Categories , There are many applications . Our most common and easiest way is to MySql in ID ,parentID, ...

  2. MySQL Summary of optimization experience and methods

    One . Server hardware pair MySQL The impact of performance   1. Disk seek capability ( disk I/O), At the current high speed SCSI Hard disk (7200 turn / second ) For example , This kind of hard disk theoretically searches every second 7200 Time , This is determined by physical properties , There is no way to change . MySQL ...

  3. PHP Infinite classification spanning tree method , Non recursive , quote

    // This is the core approach function generateTree($items){     $tree = array();     foreach($items as $item){         ...

  4. php part , A recursive infinite classification method

    <?php $data[]=array('id'=>1,'parentid'=>0,'name'=>' China '); $data[]=array('id'=>2,'paren ...

  5. PHP Achieve unlimited classification

    PHP Achieve unlimited classification Infinite classification recursive Infinite classification is a design skill , It is often used in development , for example : Website directory . Sector structure . The article classification . I think it plays an important role in designing the hierarchical structure of tables , For example, on some platforms , Fill in the invitation ...

  6. PHP Infinite classification spanning tree method , Unlimited rating

    Are you still using the time-consuming and memory wasting recursive traversal infinite classification , After reading this article , I think you should change . This is my in OSChina I saw a very concise paragraph on the Internet PHP Infinite classification spanning tree method , I happen to quote , Sort out and share . function g ...

  7. PHP Infinite classification spanning tree method

    Are you still using the time-consuming and memory wasting recursive traversal infinite classification , After reading this article , I think you should change . This is my in OSChina I saw a very concise paragraph on the Internet PHP Infinite classification spanning tree method , Sort out and share . function genera ...

  8. Share an awesome PHP Infinite classification spanning tree method , Use quotation skillfully ( turn )

    Are you still using the time-consuming and memory wasting recursive traversal infinite classification , After reading this article , I think you should change . This is my in OSChina I saw a very concise paragraph on the Internet PHP Infinite classification spanning tree method , I happen to quote , Sort out and share . function g ...

  9. MySQL Change password method summary

    This article summarizes and introduces MySQL How to change the password , It is divided into MySQL5.7 Before the release and MySQL5.7 How to modify after version , If you need help, you can refer to MySQL5.7 How to change the password before version : Method 1: use SET ...

Random recommendation

  1. The finger of the sword Offer Interview questions :21. Print binary tree from top to bottom

    One . subject : Print binary tree from top to bottom subject : Print each node of the binary tree from top to bottom , Nodes on the same layer are printed from left to right . For example, enter the binary tree in the figure below , Then print out 8.6.10.5.7.9.11. The definition of a binary tree node is as follows , use ...

  2. Use Quartz.net Dynamic setting timing time problem

    About use Quartz.net There's no need to explain .. In response to customer needs .. Need to do an interface to set the timing time . So I'm at Baidu .. use CronExpression Class can set the time ... I know that this class has well-defined fields .. No ...

  3. Direct file to Azure Storage Of Blob In service

    ( This article is also published in my official account of WeChat “dotNET Daily essays ”, Welcome to the QR code on the right .) . : To celebrate the appreciation function of WeChat official account , I'd like to share some experience of my recent work : How to upload files directly from the browser to Azure ...

  4. jquery The form of the plug-in changes color every other line and is highlighted by mouse

    The plug-in is written by the author of this blog , The purpose is to improve the author's js Ability , Also give some js Rookies provide some convenience when using plug-ins , Let the old bird fly by leisurely . The purpose of this plug-in is to change the color of the table , And when the mouse moves over a row of the table , The line can be highlighted . The whole code is like ...

  5. python Mapping and collection types of core programming learning records

    The dictionary is python The only type of mapping in

  6. android64 Bit machine compatible 32 position .so The library files

    http://blog.csdn.net/vhawk/article/details/49964475 When the monkey calls the Gaud map , Encountered an operating system compatibility issue , The exception stack says it can't be found so The library files , Monkeys don't understand , ...

  7. CoffeeScript NgComponent

    Angular run into sb. CoffeeScript - NgComponent encapsulation CoffeeScript Is based on JavaScript It's an extended compact language , It needs to be compiled into JavaScript, Then run with the browser or ...

  8. BZOJ3545&amp;3551[ONTAK2010]Peaks——kruskal Refactoring tree + Chairman tree +dfs order + On the tree

    Title Description stay Bytemountains Yes N Mountains , Every mountain has its height h_i. Some peaks are connected by two-way roads , common M Paths , Each path has a difficulty value , The higher the value, the harder it is to walk , Now there is Q Group inquiry , Each group asked from v Start only ...

  9. Consider the past you shall know the future --JavaScript Digest ( 3、 ... and )

    Preface It has been almost a year since I graduated from Tencent , Contact with a lot of projects , Also accumulated a lot of practical experience , There is a big improvement in the way we deal with problems . Over time , More and more important to discover the basic knowledge , Many problems encountered in the development process are caused by the most basic knowledge ...

  10. Nine school simulation —— The restaurant (restaurant)

    1 The restaurant (restaurant) 1.1 Background   Copper penguin is the owner of penguin restaurant , He is planning how to increase his earnings this year . 1.2 Title Description   share n Grow food , A dish i Need to spend ti The seeds are sown continuously for 24 hours , Apply fertilizer ...