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

yipeiwu_com6年前PHP代码库
我们要做一个商品的无限分类
首先数据库字段为:
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支持分块与断点续传文件下载功能代码

本文章要介绍了这篇文章是一篇关于php流下载,就是可以支持分块与断点续传文件下载,有需要的朋友可以看看。代码如下 复制代码 代码如下: $dowmFile = dirname ( __F...

Eclipse中php插件安装及Xdebug配置的使用详解

Eclipse中php插件安装及Xdebug配置的使用详解

由于在android开发团队,又迷上了android自动化测试,所有一直使用Eclipse做为开发工具。以前使用Zend Studio 9.0.1做为PHP的开发工具,现在放弃使用Zen...

php.ini中date.timezone设置详解

date.timezone设置php5默认date.timezone为utc,改为date.timezone = PRC即可解决时间相差八小时的问题,但我在php的官方文档中看了半天也没...

PHP模拟http请求的方法详解

本文实例讲述了PHP模拟http请求的方法。分享给大家供大家参考,具体如下: 方法一:利用php的socket编程来直接给接口发送数据来模拟post的操作。 建立两个文件post.php...

php中json_encode处理gbk与gb2312中文乱码问题的解决方法

本文讲述了php中json_encode处理gbk与gb2312中文乱码问题的解决方法,具体方法如下: 1.json_encode()中文在gbk/gb2312中对中文返回为null...