php递归无限极分类
2024-09-10 09:52:52
递归无限级分类有几种形式,我这里仅仅举例比較经常使用的三种:
第一种:返回有排序的数组:
<?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;
}
最新文章
- MapWinGIS.ocx 注册
- typedef 深入剖析
- Linux关闭防火墙、SELinux
- asp.net中Get请求和Post请求
- Linux使用SSH远程连接方式和更改密码 ,自己空间转移过来的。
- 基于live555的一个简单RTSP服务器
- SPRING+JNDI+C3P0 in tomcat6
- js获取手机重力感应api
- WHM API 1 - createacct
- which命令实战及原理详解-PATH实战配置
- C++对C的函数拓展 - 默认参数
- 网易面经(Java开发岗)
- 第19章:MongoDB-聚合操作--聚合管道--$limit+$skip
- UEFI启动
- Java基础-Collection子接口之List接口
- 项目Alpha冲刺——代码规范、本次冲刺任务与计划
- java基础--配置环境变量的意义
- SP2-0734: unknown command beginning ";lsnrctl st..."; - rest of line ignored.
- Hdfs&;MapReduce测试
- 爬虫框架Scrapy之Downloader Middlewares
热门文章
- BZOJ_2434_[NOI2011]_阿狸的打字机_(AC自动机+dfs序+树状数组)
- ajax post提交数据, input type=submit 返回prompt aborted by user
- ArcGIS.Server.9.3和ArcGIS API for JavaScript地图实现Toorbar功能(四)
- 动态加载dll--不占用文件
- WPF学习笔记 - 在XAML里绑定
- Print the numbers between 30 to 3000.
- HDU4289 Control 最大流
- lightoj 1017
- CVTE面试经历
- matlab 函数说明&mdash;ordfilt2