PHP implementation of the infinite level of classification code of recursive method

  • 2020-03-31 21:29:21
  • OfStack

Thought the function of this seems to be very difficult, also done before an encyclopedia, which also involves the function of the classification, but not infinite level classification, but simple three-level classification, the fixation was their own design, want to think of implementation method is too soil, actually three-level classification also just infinite levels of classification of a special case. After a period of time to consider, there have been some lines, to the Internet, the original such things omnipresent, ha ha. In fact, the infinite drop-down list function is very simple, just use a recursive algorithm.
First, to design the database, we need to set up a table to store the classification information. At least 3 fields are needed, the first is the primary key (ID), the second is the parent classification ID (parentid), and the third is the name of the classification (classname). One possible effect is:
ID PARENTID CLASSNAME
1, 0, class A
Class B
3, 1, class A
4, 1, class B
Main idea: first, look at the third and fourth lines. The value of PARENTID is 1, which means it belongs to the subclass of ID =1. However, the value of PARENTID in lines 1 and 2 is 0, which means the primary classification. The end result is:
The preliminary classification A
├ ─ ┴ second category A
├ ─ ┴ subtype B
Preliminary class B
And then there's the program, which is in PHP, which is a description language, and you can easily change it to another language, because it's similar, it's just a recurrence.
 
<?php 
$dbhost = "localhost"; //Database host name
$dbuser = "root"; //Database user name
$dbpd = "123456"; //Database password
$dbname = "test"; //The database name
mysql_connect($dbhost,$dbuser,$dbpd); //Connection between a host
mysql_select_db($dbname); //Select database
mysql_query("SET NAMES 'utf8'"); 
display_tree(" ├ ",0); 
function display_tree($tag,$classid) { 
$result = mysql_query(" 
SELECT * 
FROM ylmf_class 
WHERE parentid = '" . $classid . "' 
;" 
); 
while ($row = mysql_fetch_array($result)) { 
//Indent the node name
echo $tag.$row['classname'] . "<br/>"; 
//Call this function again to display the child nodes of the child node
display_tree($tag."  ─   ┴  ",$row['id']); 
} 
} 
?> 

This recursive method is a burden for a large number of subcolumns, some mature CMS. It is easy to call the production array, but also can greatly improve the efficiency.

Related articles: