Table of Contents
Detailed explanation of examples of infinite classification in php mysql
Home Backend Development PHP Tutorial Detailed explanation of infinite classification examples in php mysql_PHP tutorial

Detailed explanation of infinite classification examples in php mysql_PHP tutorial

Jul 13, 2016 am 10:01 AM
php+mysql main Classification Example accomplish article unlimited Detailed explanation

Detailed explanation of examples of infinite classification in php mysql

This article mainly introduces the method of realizing infinite classification in php mysql, and analyzes the mysql database design, database operation and infinite classification with examples. The specific implementation steps are of great practical value. Friends in need can refer to them

The example in this article describes the method of realizing unlimited classification in php mysql. Share it with everyone for your reference. The specific analysis is as follows:

1. The database performs unique indexing by setting the parent class ID, and then uses recursive calls of functions to achieve unlimited classification;

2. The database design is arranged in a specific format, and then uses mysql to query the key function: concat. The program implementation is relatively simple. First, we assume that there is such a three-level classification, News→PHP News→PHP6.0 is out.

If we want to find the news "PHP6.0 is out", we can click on the news first, and then click on the PHP news to find out. In other words, we can go down level by level through the grandfather class. In turn, as long as we know the parent class of a subclass, we can find it. In this way, when designing the database, we can design an additional field for the parent class id to achieve unlimited classification.

The database code is as follows:

Here we create a table "class"

The code is as follows:

CREATE TABLE `class` (
`id` int(11) NOT NULL auto_increment COMMENT 'category id',
`f_id` int(11) NOT NULL COMMENT 'parent id',
`name` varchar(25) collate gbk_bin NOT NULL COMMENT 'Category name',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=gbk COLLATE=gbk_bin AUTO_INCREMENT=1 ;
First, we insert the "News" category into the database. Because "News" is the largest category and there is no parent category on it, so I set its f_id to 0.

The code is as follows:

INSERT INTO `class` (`id`, `f_id`, `name`) VALUES(1, 0, 'News'); //The id field grows automatically and no value is required.

Then we insert the category 'PHP News' into the database. The id of its parent category 'News' is 1, so its f_id is set to 1.

The code is as follows:

INSERT INTO `class` (`id`, `f_id`, `name`) VALUES(2, 1, 'PHP News');

Then we insert the category 'PHP 6.0 is out' into the database. The id of its parent category 'PHP News' is 2, so its f_id is set to 2.

The code is as follows:

INSERT INTO `class` (`id`, `f_id`, `name`) VALUES(3, 2, 'PHP6.0 is out');

Similarly, we can insert categories all the way down, thus reaching infinite categories.

We can find that the key to inserting a category is to find the id of the parent category of this category, and then use it as the value of the f_id field of this category.

Suppose you want to insert the category 'Technology' at the same level as 'News', that is to say it is also the largest category and there is no parent category above it, then its f_id is also set to 0;

Copy the code The code is as follows:

INSERT INTO `class` (`id`, `f_id`, `name`) VALUES(4, 0, 'Technology');

There is another category 'PHP Technology' under 'Technology', so how do we insert it? First find the id of the parent class 'Technology' of 'PHP Technology', and then use it as the value of its own f_id field.

The code is as follows:

INSERT INTO `class` (`id`, `f_id`, `name`) VALUES(5, 4, 'PHP Technology');

Seeing this, everyone should understand how to insert each category into the database, so I won’t give examples. We already know how to insert each category into the database, so how do we list each category?

The code is as follows:

header("Content-type:text/html;charset=utf-8");
$db=new mysqli("localhost","root","","news_php100"); //Instantiate a database connection. Before using this, make sure that the mysqli class library has been loaded, or connect using mysql_connect.
if(mysqli_connect_errno()){
echo "Link failed:".mysqli_connect_error();
exit(); }
$db->query("set names utf8");
$result=$db->query("select name from class where f_id=0"); //Find the category with f_id=0, that is, find each major category.
while($row=$result->fetch_assoc()){
echo $row['name']."
"; //This will loop out each major category.
}
//Similarly we can loop out the subcategories of news.
$result=$db->query("select * from class where f_id=1"); //Find the category of f_id=1, that is, find the subcategory of 'News'.
while($row=$result->fetch_assoc()){
echo $row['name']."
"; //This loops out the subclasses of 'News'. Note: only subclasses, excluding grandchild classes.
}
//Writing here, we will find a problem. If this classification is a 10-level classification, do we have to write 10 loops to cycle out each of its subcategories? If there are more levels of classification, it is obviously unrealistic to write like this.
//Then what is the solution? We can write a recursive function, pass in f_id as a parameter, and continuously loop through the value of each f_id, that is to say, loop out the subclass of each f_id value.
//First we save the values ​​of each category in a two-dimensional array, which is useful in the following recursive function.
$result=$db->query("select * from class");
while($row=$result->fetch_assoc()){
$arr[]=array($row[id],$row[f_id],$row[name]); //Each row saves the information of a category's id, f_id, and name.
}
function fenlei($f_id=0){ //$f_id is initialized to 0, that is, the cycle starts from the maximum classification.
global $arr; //Declare $arr as a global variable before it can be referenced in the function.
for($i=0;$i if($arr[$i][1]==$f_id){ //$arr[$i][1] represents the value of f_id of the $i-th category. Start with $f_id=0, that is, output the classification of f_id=0.
echo $arr[$i][2]."
"; //$arr[$i][1] represents the value of the name of the $i-th category.
fenlei($arr[$i][0]); //$arr[$i][1] represents the value of the id of the $i-th category. Perform recursion, that is, use your own id as the f_id parameter to recycle your own subclasses.
}
}
}
?>
The three fields id, parentid, name, the algorithm is also very simple and recursive. In the past, it was very stupid when using recursion, I should say extremely stupid, because in recursion, all the subclasses were obtained by querying the data table. Recently, I got the idea and thought of a The method that everyone on earth can think of, the following is the code, a class, the code is as follows:

Copy the code The code is as follows:

class Tree {

/**
* All classification information queried from the database
* @var array
*/
var $arr;
/**
* The following format
* var $arr = array(
1 => array('id'=>'1','parentid'=>0,'name'=>'First-level column one'),
2 => array('id'=>'2','parentid'=>0,'name'=>'First-level column two'),
3 => array('id'=>'3','parentid'=>1,'name'=>'Second-level column one'),
);*/

/**
* Output structure
* @var array
*/
var $tree = array();
/**
* Depth of tree recursion
* @var int
*/
var $deep = 1;

/**
* Generate tree-shaped modification symbols
* @var array
*/
var $icon = array('│','├','└');
/**
* Generate a subordinate tree structure of the specified id
* @param int $rootid To get the id of the tree structure
* @param string $add prefix used in recursion
* @param bool $parent_end identifies whether the parent category is the last one
*/
function getTree($rootid = 0,$add = ”,$parent_end =true){
$is_top = 1;
$child_arr = $this->getChild($rootid);
if(is_array($child_arr)){
$cnt = count($child_arr);
foreach($child_arr as $key => $child){
$cid = $child['id'];
$child_child = $this->getChild($cid);
if($this->deep >1){
if($is_top == 1 && $this->deep > 1){
$space = $this->icon[1];
if(!$parent_end)
$add .= $this->icon[0];
else $add .= ' ';
}

if($is_top == $cnt){
$space = $this->icon[2];
$parent_end = true;
}else {
$space = $this->icon[1];
$parent_end = false;
}
}
$this->tree[] = array('spacer'=>$add.$k.$space,
'name'=>$child['name'],
'id'=>$cid
);
$is_top ;

$this->deep ;
if($this->getChild($cid))
$this->getTree($cid,$add,$parent_end);
$this->deep–;
}
}
return $this->tree;
}

/**
* Get the lower-level classification array
* @param int $root
*/
function getChild($root = 0){

$a = $child = array();
foreach($this->arr as $id=>$a){
if($a['parentid'] == $root){
$child[$a['id']] = $a;
}
}
return $child?$child:false;
}
/**
* Set source array
* @param $arr
*/
function setArr($arr = array()){
$this->arr = $arr;
}
}
?>
通过一次查询把结构保存进一个数组,再数组进行递归运算,无疑极大的提高了程序运行效率,使用代码很简单.

 

希望本文所述对大家的php程序设计有所帮助。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/971936.htmlTechArticlephp mysql实现无限分类实例详解 这篇文章主要介绍了php mysql实现无限分类的方法,实例分析了mysql数据库设计、数据库操作及无限极分类的具体...
Statement of this Website
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

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 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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

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

How can I make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! How can I make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! Mar 15, 2024 pm 04:13 PM

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,

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

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

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

See all articles