PHP returns an infinite class back to a string or an array instance recursively

Source: Internet
Author: User
Tags arrays php file string format

In some complex systems, it is required to classify the information columns in an infinite level to enhance the flexibility of the system. So how does PHP achieve an infinite level of classification? We use recursive algorithm in this paper and combine the MySQL data table to achieve the infinite classification.

Recursion, simply is a piece of program code repeated calls, when the code to write to a custom function, the parameters such as variables to save, function repeatedly call the function, 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: Category number, primary key from growth; title: category name; PID: the owning parent category ID.

Class table structure:

CREATE TABLE IF not EXISTS ' class ' (
' ID ' mediumint (6) Not NULL auto_increment,
' title ' varchar Not NULL,
' PID ' Mediumint (6) Not NULL DEFAULT ' 0 ',
PRIMARY KEY (' id ')
) Engine=myisam DEFAULT Charset=utf8;

After inserting the data, as shown in the figure:

Php

Depending on the requirements, we provide two different forms of custom functions, one is to return the string, one is to return the array, both of the functions use recursive methods. 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);//queries the classification of the PID subclasses
    if ($result && mysql_affected_rows ()) {//If there are subclasses
         $str. = ' <ul> ';
        while ($row = Mysql_fetch_array ($result)) {//circular Recordset
  & nbsp;         $str. = "<li>". $row [' id ']. "--" . $row [' title ']. "</li>"; Build string
            get_str ($row [' id ']);//Call GET_STR () , pass the ID parameter in the recordset to the function, and continue querying the lower
       }
         $str. = ' </ul> ';
   }
    return $str;
}

The above function get_str () through recursion, continuously inquires the subordinate classification, and finally returns the string, everybody can revise the STR according to the project demand, finally produces an infinite rank list:

Include_once (' connect.php '); Connect database, connect.php file write one yourself.
echo get_str (0); Output Infinite Level classification

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);//Query Subclass
$arr = Array ();
if ($result && mysql_affected_rows ()) {//If there are subclasses
while ($rows =mysql_fetch_assoc ($result)) {//circular Recordset
$rows [' list '] = Get_array ($rows [' id ']); Call function, pass parameter, continue query subordinate
$arr [] = $rows; Combining arrays
}
return $arr;
}
}

function Get_array () returned the array, which is what we expected, so the author recommends using Get_array () to get the array, so that we can do any operation on the array, for example, we can convert arrays into JSON-formatted data to the front page, The front-end page can display the classification information flexibly by parsing the JSON data. For example, the tree structure of the classification list, Drop-down category list, and so on.

Include_once (' connect.php '); Connecting to a database
$list = Get_array (0); Call function
Print_r ($list); Output array

Output effects such as:

If you want to output JSON-formatted data, you can use:

echo Json_encode ($list);

For example, in the actual use of drift, the infinite level of classification into the SELECT element:

Recursive infinite-pole Read all groupings
$qian _i=0;
function get_group_str ($id = 0) {
Global $conn, $qian _i;
$sql = "SELECT * from ' group ' where fid= $id";
$result = mysql_query ($sql);//Query the classification of the subclasses of the PID
if ($result && mysql_affected_rows ()) {//If there are subclasses
$qian _i++;
while ($row = Mysql_fetch_array ($result)) {//circular Recordset
$qian = Str_repeat (" ", ($qian _i-1) *6);
$str. = "<option value= '". $row [' id ']. "' > $qian." $row [' title ']. "</option>"; Build string
$str. = Get_group_str ($row [' id ']); Recursively call the function itself, pass the ID parameter in the recordset to the function, and continue querying the subordinate
}
$qian _i--;
}
return $str;
}
$opt = "<option value= ' 0 ' > top group </option>";
$opt. =GET_GROUP_STR (0);

Note that in actual use, convert the red Full-width space code above to Half-width code.

Effect Chart:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.