Home >Backend Development >PHP Tutorial >Using PHP recursion to achieve infinite classification Detailed explanation of formatted array_PHP tutorial
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
<PRE class=php name="code"> ;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>)
<?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 '< ;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