This article is a detailed analysis of the use of php recursion to implement unlimited classification and formatting arrays. For more information, see how to create an unlimited product category.
First, the database field is:
Id ---------- commodity primary key id
Fid ---------- Product parent id
Name ---------- Product name
The final output array format is
The code is as follows:
Array (
0 => array (
'Id' => 1,
'Fid' => 0,
'Name' => 'French logs'
'Child '=> array (
0 => array (
'Id' => 12,
'Fid' => 1,
'Name' => 'Perfume'
'Child '=> array (
0 => array (
'Id' => 34,
'Fid' => 12,
'Name' => 'female perfume'
)
)
),
1 => array (
'Id' => 13,
'Fid' => 1,
'Name' => 'Notebook'
'Child '=> NUll
)
)
),
1 => array (), // The format is the same as above. it makes no sense that I will not repeat it.
2 => array ()
)
Php code:
// The mysql PDO used by the database is the same as the whole idea.
$ Conn = mysql_connect ('localhost', 'root', '123 ');
If (mysql_errno ()){
Printf ('connection failed'. mysql_error ());
}
Mysql_select_db ('edeng ');
Mysql_set_charset ('utf8 ');
/*
* Recursive functions
* @ Param id: to query all fid = $ id sub-classes, set the default value of $ id to 0 because I set the fid of the top-level category to 0 in the database.
*/
Function get_array ($ id = 0 ){
$ SQL = "select id, fid, cname from e_cat where fid = $ id ";
$ Result = mysql_query ($ SQL );
$ Arr = array ();
If ($ result & mysql_affected_rows ()){
While ($ rows = mysql_fetch_assoc ($ result )){
$ Rows ['child '] = get_array ($ rows ['id']);
$ Arr [] = $ rows;
}
Return $ arr;
}
}
Echo'';
$result = get_array();
print_r($result);
The function first queries all classes whose fid is 0.
Call back one by one while to find the subclass whose fid is the id of the current class.