第11课 文章分类(组件化开发) Thinkphp5商城第四季

[TOC]

思路:

  1. 控制器查出所有数据后调用扩展类里的无限级分类 public function catetree($cateRes) 方法.
    把排序好的数据传给视图层.
  2. 视图层用str_repeat()做好层级显示

控制器里

<?php
namespace app\admin\controller;

use catetree\Catetree; //引入扩展类
use think\Controller;

class Cate extends Controller
{
public function lst()
    {
        $cate = new Catetree(); //实例化引入的Catetree类
        $cateObj = db('cate');       
        $cateRes = $cateObj->order('sort DESC')->select(); //查所有数据
        $cateRes = $cate->catetree($cateRes); //调用无限级分类
        $this->assign([
            'cateRes' => $cateRes, //传到视图层
        ]);
        return view('list');
    }

扩展类里:

D:\xampp\htdocs\shop\extend\catetree\Catetree.php

<?php
namespace catetree;

use think\Validate;

class Catetree
{

    public function catetree($cateRes)
    {
        return $this->sort($cateRes);
    }

    public function sort($cateRes, $pid = 0, $level = 0)
    {

        static $arr = array();
        foreach ($cateRes as $k => $v) {
            if ($v['pid'] == $pid) {
                $v['level'] = $level;
                $arr[] = $v;
                $this->sort($cateRes, $v['id'], $level + 1);
            }
        }

        return $arr;
    }

视图层:

<td><?php echo str_repeat('-', $cate['level']*8)?>{$cate.cate_name}</td>

效果:

posted @ 2018-09-19 06:57  HaimaBlog  阅读(439)  评论(0编辑  收藏  举报