We want 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
Copy codeThe code is as follows: <PRE class = php name = "code"> <PRE class = php name = "code"> 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 ()
) </PRE> <BR>
<PRE> </PRE>
<PRE> </PRE>
Php code:
<P> </P>
<P> </P>
<PRE class = php name = "code"> <? Php
// 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 '<pre> ';
$ Result = get_array ();
Print_r ($ result );
</PRE> <BR>
<BR>
<P> </P>
<P> </P>
<P> the function first queries all classes whose fid is 0 </P>
<P> call back the fid as the id subclass of the current class through the while loop. </P>
<P> <BR>
</P>
<P> <BR>
</P>
<BR>
<BR>
<PRE> </PRE>
</PRE>