Using php Recursion to implement unlimited classification and formatting of Arrays

Source: Internet
Author: User

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>

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.