递归无限级分类有几种形式,我这里仅仅举例比較经常使用的三种:

第一种:返回有排序的数组:

<?php

$data = array(
1 => array(
'id' => 1,
'pid' => 0,
'user_name' => 'one',
),
2 => array(
'id' => 2,
'pid' => 1,
'user_name' => 'two',
),
3 => array(
'id' => 3,
'pid' => 1,
'user_name' => 'two',
),
4 => array(
'id' => 4,
'pid' => 2,
'user_name' => 'three',
),
5 => array(
'id' => 5,
'pid' => 2,
'user_name' => 'three',
),
6 => array(
'id' => 6,
'pid' => 5,
'user_name' => 'four',
),
); function genCate( $data, $pid = 0, $level = 0 ) {
static $result = array();
$result = ($level == 0) ? array() : $result;
$prefix = ($level == 0) ? '' : str_repeat( '-', $level );
foreach ( $data as $key => $row ) {
if ( $row['pid'] == $pid ) {
$row['user_name'] = $prefix . $row['user_name'];
$result[] = $row['user_name'];
genCate( $data, $row['id'], $level + 1 );
}
}
return $result;
} echo '<pre>';
$result = genCate( $data );
print_r( $result );
exit;
?>

另外一种:返回html字符串形式:

function getTreeHtml( $data, $pId ) {
$html = '';
foreach ( $data as $k => $v ) {
if ( $v['pid'] == $pId ) {
$html .= "<li>" . $v['user_name'];
$html .= getTree( $data, $v['id'] );
$html = $html . "</li>";
}
}
return $html ? '<ul>' . $html . '</ul>' : $html;
}

第三种:返回多维数组形式:

function getTreeArray( $data, $pId = 0 ) {
$tree = array();
foreach ( $data as $key => $value ) {
if ( $value['pid'] == $pId ) {
$value['childrens'] = getTreeArray( $data, $value['id'] );
$tree[] = $value;
}
}
return $tree;
}

最新文章

  1. MapWinGIS.ocx 注册
  2. typedef 深入剖析
  3. Linux关闭防火墙、SELinux
  4. asp.net中Get请求和Post请求
  5. Linux使用SSH远程连接方式和更改密码 ,自己空间转移过来的。
  6. 基于live555的一个简单RTSP服务器
  7. SPRING+JNDI+C3P0 in tomcat6
  8. js获取手机重力感应api
  9. WHM API 1 - createacct
  10. which命令实战及原理详解-PATH实战配置
  11. C++对C的函数拓展 - 默认参数
  12. 网易面经(Java开发岗)
  13. 第19章:MongoDB-聚合操作--聚合管道--$limit+$skip
  14. UEFI启动
  15. Java基础-Collection子接口之List接口
  16. 项目Alpha冲刺——代码规范、本次冲刺任务与计划
  17. java基础--配置环境变量的意义
  18. SP2-0734: unknown command beginning &quot;lsnrctl st...&quot; - rest of line ignored.
  19. Hdfs&amp;MapReduce测试
  20. 爬虫框架Scrapy之Downloader Middlewares

热门文章

  1. BZOJ_2434_[NOI2011]_阿狸的打字机_(AC自动机+dfs序+树状数组)
  2. ajax post提交数据, input type=submit 返回prompt aborted by user
  3. ArcGIS.Server.9.3和ArcGIS API for JavaScript地图实现Toorbar功能(四)
  4. 动态加载dll--不占用文件
  5. WPF学习笔记 - 在XAML里绑定
  6. Print the numbers between 30 to 3000.
  7. HDU4289 Control 最大流
  8. lightoj 1017
  9. CVTE面试经历
  10. matlab 函数说明&mdash;ordfilt2