之将分类按级别输出实例

php教程评论374 views阅读模式

本文主要和大家分享Thinkphp递归处理之将分类按级别输出实例,希望能帮助到大家。

1.一般在数据库中存储分类,分类之间的关系用parent_id来标识。在开发中有时需要根据分类的级别,展示分类,如下图:

使用递归方法,源代码如下:

  1. /** 
       *  
       * @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();

前台文件显示代码

  1. <table>  
    <foreach name="list" item="vo">  
        <tr>  
            <td>  
                <for start="1" end="$vo['level']">  
                    &nbsp;&nbsp;&nbsp;&nbsp;  
                </for>  
                {$vo.cat_name}<br/>  
            </td>  
        </tr>  
    </foreach>  
    </table>

这里语法使用的是Thinkphp

以上就是之将分类按级别输出实例的详细内容,更多请关注php教程网其它相关文章!

企鹅博客
  • 本文由 发表于 2020年6月26日 19:39:02
  • 转载请务必保留本文链接:https://www.qieseo.com/246201.html

发表评论