Using php recursion to implement unlimited classification and formatting of arrays

Source: Internet
Author: User
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.













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.