search
HomeBackend DevelopmentPHP TutorialSummary of methods to implement unlimited classification in PHP+Mysql_PHP tutorial

Summary of methods to implement unlimited classification in PHP+Mysql_PHP tutorial

Jul 13, 2016 am 10:06 AM
php+mysqlClassificationaccomplisharticlemethodunlimitedSummaryof

A summary of methods to achieve unlimited classification in PHP+Mysql

This article mainly introduces two methods to achieve unlimited classification in PHP+Mysql, and compares and analyzes the two methods. Friends who need it can refer to the advantages and disadvantages of the method

Infinite classification is an old topic. Let’s take a look at how to implement it with PHP combined with Mysql.

The first method

This method is very common and traditional. Let’s look at the table structure first

Table:category
id int primary key, auto-increment
name varchar category name
pid int parent class id, default 0
The pid of the top category is 0 by default. When we want to take out the sub-category tree of a certain category, the basic idea is recursion. Of course, due to efficiency issues, it is not recommended to query the database for every recursion. The usual approach is to first retrieve all categories and save them in a PHP array. , and then process it, and finally cache the results to improve the efficiency of the next request.

First build an original array, which can be pulled directly from the database:

The code is as follows:


$categories = array(
array('id'=>1,'name'=>'Computer','pid'=>0),
array('id'=>2,'name'=>'mobile phone','pid'=>0),
array('id'=>3,'name'=>'Notebook','pid'=>1),
array('id'=>4,'name'=>'Desktop','pid'=>1),
array('id'=>5,'name'=>'Smartphone','pid'=>2),
array('id'=>6,'name'=>'Function machine','pid'=>2),
array('id'=>7,'name'=>'Ultrabook','pid'=>3),
array('id'=>8,'name'=>'Game Note','pid'=>3),
);

The goal is to convert it into the following structure

Computer
Notebook
Ultrabook
Game notebook
Desktop
Mobile phone
Smartphone
Function phone
If represented by an array, you can add a children key to store its subcategories:

The code is as follows:


array(
//1 corresponds to the id, which is convenient for direct reading
1 => array(
'id'=>1,
'name'=>'Computer',
'pid'=>0,
children=>array(
&array(
'id'=>3,
'name'=>'Notebook',
'pid'=>1,
'children'=>array(
//Omit here
)
),
&array(
'id'=>4,
'name'=>'Desktop',
'pid'=>1,
'children'=>array(
//Omit here
)
),
)
),
//Other categories are omitted
)

Processing process:

The code is as follows:


$tree = array();
//The first step is to use the classification id as the array key and create the children unit
foreach($categories as $category){
$tree[$category['id']] = $category;
$tree[$category['id']]['children'] = array();
}
//The second part uses references to add each category to the children array of the parent class, so that a tree structure can be formed in one traversal.
foreach ($tree as $k=>$item) {
if ($item['pid'] != 0) {
$tree[$item['pid']]['children'][] = &$tree[$k];
}
}
print_r($tree);

The printing results are as follows:

The code is as follows:


Array
(
[1] => Array
(
[id] => 1
[name] => Computer
[pid] => 0
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => Notebook
[pid] => 1
[children] => Array
(
[0] => Array
(
[id] => 7
[name] => Ultrabook
[pid] => 3
[children] => Array
(
)
)
[1] => Array
(
[id] => 8
[name] => Game Notebook
[pid] => 3
[children] => Array
(
)
)
)
)
[1] => Array
(
[id] => 4
[name] => Desktop
[pid] => 1
[children] => Array
(
)
)
)
)
[2] => Array
(
[id] => 2
[name] => Mobile phone
[pid] => 0
[children] => Array
(
[0] => Array
(
[id] => 5
[name] => Smartphone
[pid] => 2
[children] => Array
(
)
)
[1] => Array
(
[id] => 6
[name] => Function phone
[pid] => 2
[children] => Array
(
)
)
)
)
[3] => Array
(
[id] => 3
[name] => Notebook
[pid] => 1
[children] => Array
(
[0] => Array
(
[id] => 7
[name] => Ultrabook
[pid] => 3
[children] => Array
(
)
)
[1] => Array
(
[id] => 8
[name] => Game Notebook
[pid] => 3
[children] => Array
(
)
)
)
)
[4] => Array
(
[id] => 4
[name] => Desktop
[pid] => 1
[children] => Array
(
)
)
[5] => Array
(
[id] => 5
[name] => Smartphone
[pid] => 2
[children] => Array
(
)
)
[6] => Array
(
[id] => 6
[name] => Function phone
[pid] => 2
[children] => Array
(
)
)
[7] => Array
(
[id] => 7
[name] => Ultrabook
[pid] => 3
[children] => Array
(
)
)
[8] => Array
(
[id] => 8
[name] => Game Notebook
[pid] => 3
[children] => Array
(
)
)
)

Advantages: The relationship is clear and it is easy to modify the relationship between superiors and subordinates.

Disadvantages: Using PHP for processing, if the number of categories is huge, the efficiency will also be reduced.

The second method

This method is to add a path field to the table field:

Table:category
id int primary key, auto-increment
name varchar category name
pid int parent class id, default 0
path varchar path
Sample data:

id name pid path
1 computer 0 0
2 mobile 0 0
3 notebook 1 0-1
4 Ultrabook 3 0-1-3
5 Game Book 3 0-1-3
The path field records the path from the root category to the upper-level parent category, represented by id+'-'.

In this way, assuming we want to query all descendant categories under the computer, we only need one sql statement:

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 | Notebook | 0-1 |
| 4 | Ultrabook | 0-1-3 |
| 5 | Game Book | 0-1-3 |
+----+-----------+-------+
This method has also been adopted by many people. I summarized it as follows:

Advantages: easy query, high efficiency, path field can be indexed.

Disadvantages: Updating node relationships is troublesome and requires updating the path fields of all descendants.

The above is the entire content of this article, two methods, which one do you prefer? Hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/962922.htmlTechArticleA summary of methods to achieve unlimited classification in PHP+Mysql. This article mainly gives you a summary of how to achieve unlimited classification in PHP+Mysql. Two methods, and comparative analysis of the advantages and disadvantages of the two methods, friends in need can...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

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

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools