Using PHP recursion to realize infinite classification format array of detailed _php skills

Source: Internet
Author: User
We're going to do an infinite assortment of merchandise.
First database field:
ID----------Commodity primary Key ID
FID----------Product Parent ID
Name----------Commodity Name
the last output is in the array format
Copy Code code as follows:

<pre class=php name= "code" ><pre class=php name= "code" >array (
0=>array (
' ID ' =>1,
' FID ' =>0,
' Name ' => ' French domestics '
' 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 (),//format ditto I'm not going to repeat it. It doesn't make any sense.
2=>array ()
) </PRE><BR>
<PRE></PRE>
<PRE></PRE>
PHP Code:
<P></P>
<P></P>
<pre class=php name= "code" ><?php
Database I used the MySQL PDO but the whole idea was the same.
$conn =mysql_connect (' localhost ', ' root ', ' 123 ');
if (Mysql_errno ()) {
printf (' Connection failed '. Mysql_error ());
}
mysql_select_db (' Edeng ');
Mysql_set_charset (' UTF8 ');
/*
* Recursive function
* @param ID to query all subclasses of the fid= $id the default value for $id is set to 0 because I set the FID of the topmost 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>
The <P> function first queries all classes that have a fid of 0 </P>
<P> Loop through while loops to find the subclass of the ID of the current class </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.