利用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 获取远程文件大小的3种解决方法

1、使用file_get_contents()复制代码 代码如下:<?php$file = file_get_contents($url);echo strlen($file);?...

PHP自定义函数实现数组比较功能示例

本文实例讲述了PHP自定义函数实现数组比较功能。分享给大家供大家参考,具体如下: <?php //数组使用标准比较运算符这样比较的 function standar...

PHP中通过HTTP_USER_AGENT判断是否为手机移动终端的函数代码

有时候很实用在一些场合,留住备用吧 复制代码 代码如下:function is_mobile_request()       {&nbs...

WordPress网站性能优化指南

1.选择一个好的主机 尽量不要使用免费主机或者共享主机(Godaddy啊、Bluehost啊等等所谓无限带宽、无限网站之类的主机) 首先,你的域名和你的主机最好在一个IDC哪儿,如果不是...

PHP new static 和 new self详解

PHP new static 和 new self详解

最近在一个视频的评论被问到一个小问题:这里选择用static 而不是self有特殊的考虑么?或者我们可以这样转换一下问题: PHP 的 new static 和 new self 具体有...