网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2024/10/13 浏览:3 次 )
我们要做一个商品的无限分类
首先数据库字段为:
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>&nbsp;</P>
<P>函数首先查询出所有fid为0的类</P>
<P>通过while逐个循环进行回调查找fid为当前类的id的子类</P>
<P><BR>
</P>
<P><BR>
</P>
<BR>
<BR>
<PRE></PRE>
</PRE>

上一篇:PHP跳转页面的几种实现方法详解
下一篇:如何利用php array_multisort函数 对数据库结果进行复杂排序
一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。