PHP Recursive implementation of infinite class classification
In some complex systems, it is required to classify the information columns infinitely, in order to enhance the flexibility of the system. So how does PHP implement an infinite class classification? We use recursive algorithms in this article and combine MySQL data tables to achieve infinite classification.
Recursive, Simple is a program code repeated calls, when the code is written into a custom function, the parameters and other variables are saved, function repeatedly called functions, until a certain condition to jump out, return the corresponding data.
Mysql
First we prepare a data table class to record the product classification information. There are three fields in the table, ID: Classification number, primary key self-growth; title: category name; PID: parent category ID.
Class table structure:
CREATE TABLE IF NOT EXISTS `class` ( `id` mediumint(6) NOT NULL AUTO_INCREMENT, `title` varchar(30) NOT NULL, `pid` mediumint(6) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM
After inserting the data,
Php
Depending on the requirements, we provide two custom functions in different formats, one is the return string, the other is the return array, and both functions use a recursive method. First look at the function that returns the string format:
function get_str($id = 0) { global $str; $sql = "select id,title from class where pid= $id"; $result = mysql_query($sql);//查询pid的子类的分类 if($result && mysql_affected_rows()){//如果有子类 $str .= '
'; while ($row = mysql_fetch_array($result)) { //循环记录集 $str .= "
- " . $row['id'] . "--" . $row['title'] . "
"; //构建字符串 get_str($row['id']); //调用get_str(),将记录集中的id参数传入函数中,继续查询下级 } $str .= '
'; }
The above function get_str () recursively queries the sub-classification and eventually returns a string, which can be modified according to the requirements of the project, and eventually generate an infinite hierarchical list:
Effects such as:
Then we'll look at the function that returns the array format, using recursion as well:
function get_array($id=0){ $sql = "select id,title from class where pid= $id"; $result = mysql_query($sql);//查询子类 $arr = array(); if($result && mysql_affected_rows()){//如果有子类 while($rows=mysql_fetch_assoc($result)){ //循环记录集 $rows['list'] = get_array($rows['id']); //调用函数,传入参数,继续查询下级 $arr[] = $rows; //组合数组 } return $arr;
The function Get_array () returns an array, which is what we expect, so I recommend using Get_array () to get an array, so that we can do anything with arrays, for example, we can convert the array into JSON-formatted data to the front-end page, Front-end pages can flexibly present categorical information by parsing JSON data. such as the tree structure of the classification list, drop-down category list and so on.
Output effects such as:
If you want to output JSON-formatted data, you can use: