首页 > Web开发 > 详细

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

时间:2016-02-09 07:41:52      阅读:206      评论:0      收藏:0      [点我收藏+]
我们要做一个商品的无限分类
首先数据库字段为:
id ----------商品主键id
fid ---------- 商品父id
name ---------- 商品名
最后输出的数组格式为
复制代码 代码如下:

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

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

原文:http://www.jb51.net/article/38179.htm

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!