本文主要和大家分享Thinkphp递归处理之将分类按级别输出实例,希望能帮助到大家。
1.一般在数据库中存储分类,分类之间的关系用parent_id来标识。在开发中有时需要根据分类的级别,展示分类,如下图:

使用递归方法,源代码如下:
/**
*
* @param array $list 为一个二维数组,存放着所有的分类,包含的字段为(分类id,分类名,parent_id)
* @param number $parent_id
* @param number $level
* @return Ambigous <multitype:, number>
*/
function find_level($list,$parent_id=0,$level=1){
foreach($list as $l){
if($l['parent_id']==$parent_id){
$l['level']=$level;
$arr[]=$l;
$child=$this->find_level($list,$l['cat_id'],$level+1);
if(is_array($child)){
$arr=array_merge($arr,$child);
}
}
}
return $arr;
}在使用时,根据实际情况使用find_level($list) 或者 $this->find_level($list) 就可以了
$list=M('category')->field('cat_id,cat_name,parent_id')->select();
$list=$this->find_level($list);
$this->list=$list;
$this->display();前台文件显示代码
<table>
<foreach name="list" item="vo">
<tr>
<td>
<for start="1" end="$vo['level']">
</for>
{$vo.cat_name}<br/>
</td>
</tr>
</foreach>
</table>这里语法使用的是Thinkphp
以上就是之将分类按级别输出实例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号