Using PHP recursion to achieve infinite classification Detailed explanation of formatted array_PHP tutorial

WBOY
Release: 2016-07-21 15:07:31
Original
1025 people have browsed it

We want to make an infinite classification of products
First the database fields are:
id ----------Product primary key id
fid - --------- Product parent id
name ---------- Product name
The final output array format is

Copy code The code is as follows:

<PRE class=php name="code"&gt ;array(<BR> 0=>array(<br> 'id'=>1,<br> 'fid'=>0,<br> 'name'=>'French product'<br> 'child'=>array(<br> 0=>array( <br> 'id'=>12,<br> 'fid'=>1,<br> 'name'=>'Perfume '<br> 'child'=>array(<br> 0=>array(<br> 'id'=>34,<br> 'fid'=>12,<br> 'name'= >'Female perfume'<br> )<br> )<br> ),<br> 1=>array(<br> 'id'=>13,<br> 'fid'=>1 ,<br> 'name'=>'Notebook'<br> 'child'=>NUll<br> )<br> )<br> ),<br> 1=>array(), //Format I will not repeat the same as above, it makes no sense<br> 2=>array()<br>)



< PRE>
php code:



<?php<BR>//I use mysql PDO for the database but the whole idea is the same<BR>$conn=mysql_connect('localhost','root','123');<BR>if (mysql_errno()){<BR> printf('Connection failed'.mysql_error());<BR>}<BR>mysql_select_db('edeng');<BR>mysql_set_charset('utf8');<BR>/* <BR> *Recursive function<BR> *@param id To query all subclasses of fid=$id The default value of $id is set to 0 because I set the fid of the top-level category to 0 in the database <BR> */<BR>function get_array($id=0){<BR> $sql="select id,fid,cname from e_cat where fid= $id";<BR> $result=mysql_query($sql) ;<BR> $arr=array();<BR> if($result && mysql_affected_rows()){<BR> while($rows=mysql_fetch_assoc($result)){<br><br> $rows['child ']=get_array($rows['id']);<BR> $arr[] = $rows;<BR> }<BR> return $arr;<BR> }<BR>} <BR>echo '&lt ;pre>';<br>$result = get_array();<br>print_r($result);<br>






The function first queries all classes with fid 0


Loop one by one through while Conduct a back investigation to find the subclass whose fid is the id of the current class















www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327545.htmlTechArticleWe want to make an infinite classification of products. First, the database field is: id ---------- Product primary key id fid ---------- Product parent id name ---------- The final output array format of the product name is complex...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template