我们要做一个商品的无限分类
首先数据库字段为:
id ----------商品主键id
fid ---------- 商品父id
name ---------- 商品名
最后输出的数组格式为
<PRE class=php name="code">array(<BR> 0=>array(<BR> 'id'=>1,<BR> 'fid'=>0,<BR> 'name'=>'法国货'<BR> 'child'=>array(<BR> 0=>array( <BR> 'id'=>12,<BR> 'fid'=>1,<BR> 'name'=>'香水'<BR> 'child'=>array(<BR> 0=>array(<BR> 'id'=>34,<BR> 'fid'=>12,<BR> 'name'=>'女用香水'<BR> )<BR> )<BR> ),<BR> 1=>array(<BR> 'id'=>13,<BR> 'fid'=>1,<BR> 'name'=>'笔记本'<BR> 'child'=>NUll<BR> )<BR> )<BR> ),<BR> 1=>array(), //格式同上我就不再重复写了 没什么意义<BR> 2=>array()<BR>)
<?php<BR>//数据库我用的mysql PDO 但是整个思路又是一样的<BR>$conn=mysql_connect('localhost','root','123');<BR>if(mysql_errno()){<BR> printf('连接失败'.mysql_error());<BR>}<BR>mysql_select_db('edeng');<BR>mysql_set_charset('utf8');<BR>/*<BR> *递归函数<BR> *@param id 要查询fid=$id的所有子类 这里将$id的默认值为设为0 是因为我在数据库中将最顶层的类别的fid设置为0<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 class="brush:php;toolbar:false">';<BR>$result = get_array();<BR>print_r($result);<BR>
函数首先查询出所有fid为0的类
通过while逐个循环进行回调查找fid为当前类的id的子类