利用php递归实现无限分类 格式化数组的详解_php技巧

WBOY
Release: 2016-05-17 09:02:26
Original
915 people have browsed it

我们要做一个商品的无限分类
首先数据库字段为:
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>)
Copy after login


Copy after login
Copy after login
Copy after login

Copy after login
Copy after login
Copy after login

php代码:



<?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>
Copy after login





 


函数首先查询出所有fid为0的类


通过while逐个循环进行回调查找fid为当前类的id的子类












Copy after login
Copy after login
Copy after login



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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!