利用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>

相关文章

奉献出一个封装的curl函数 便于调用(抓数据专用)

奉献出一个封装的curl函数,便于调用 复制代码 代码如下: function curl($url, $ifpost = 0, $datafields = '', $cookiefile...

PHP配置文件中最常用四个ini函数

php的配置函数就是几个ini_*的函数,主要是针对配置文件的操作,其实就四个函数:ini_get、ini_set、ini_get_all、ini_restore。个人感觉最有用的就是i...

用php随机生成福彩双色球号码的2种方法

不瞒您说,俺也是个双色球爱好者,经常买,但迟迟没有中过一等奖,哈哈。这里为大家介绍用php随机生成福彩双色球号码的二种方法,供朋友们学习参考。新的一年,祝大家中大奖,发大财。 方法一复制...

PHP生成图片缩略图类示例

本文实例讲述了PHP生成图片缩略图类。分享给大家供大家参考,具体如下: class App_image_helper { protected $imgFileName; pr...

php实现的一个简单json rpc框架实例

json rpc 是一种以json为消息格式的远程调用服务,它是一套允许运行在不同操作系统、不同环境的程序实现基于Internet过程调用的规范和一系列的实现。这种远程过程调用可以使用h...