Using php recursion to realize the detail of infinite classification formatting array
- 2020-06-12 08:37:26
- OfStack
We're going to do an infinite class of goods
First, the database field is:
id -- Commodity primary key id
fid -- The father of the product
name -- Product name
The final output is in the form of an array
First, the database field is:
id -- Commodity primary key id
fid -- The father of the product
name -- Product name
The final output is in the form of an array
<PRE class=php name="code"><PRE class=php name="code">array(
0=>array(
'id'=>1,
'fid'=>0,
'name'=>' French goods '
'child'=>array(
0=>array(
'id'=>12,
'fid'=>1,
'name'=>' perfume '
'child'=>array(
0=>array(
'id'=>34,
'fid'=>12,
'name'=>' The female perfume '
)
)
),
1=>array(
'id'=>13,
'fid'=>1,
'name'=>' The notebook '
'child'=>NUll
)
)
),
1=>array(), // Again, I'm not going to repeat it It doesn't make sense
2=>array()
)</PRE><BR>
<PRE></PRE>
<PRE></PRE>
php Code:
<P></P>
<P></P>
<PRE class=php name="code"><?php
// I used the database mysql PDO But the whole idea is again 1 The sample of
$conn=mysql_connect('localhost','root','123');
if(mysql_errno()){
printf(' The connection fails '.mysql_error());
}
mysql_select_db('edeng');
mysql_set_charset('utf8');
/*
* Recursive function
*@param id In order to query fid=$id All subclasses of There will be $id The default value of is set to 0 Because I put the topmost category in the database fid Set to 0
*/
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 of them fid for 0 The class of </P>
<P> through while Loop back to find fid For the current class id A subclass of </P>
<P><BR>
</P>
<P><BR>
</P>
<BR>
<BR>
<PRE></PRE>
</PRE>