首页 / php开发 / php无限级分类

php无限级分类

2020-09-05 09:05 php开发 阅读 895 来源

表结构

CREATE TABLE `test`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pid` int(11) NULL DEFAULT NULL,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '名称',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

ThinkPHP5/ThinkPHP6框架举例

<?php


namespace app\common\model;


use think\Collection;
use think\Model;

class Test extends Model
{
    public static function getInfinite($pid = 0, &$result = [], $blank = 0)
    {
        $res = self::where('pid', $pid)->select();
        $blank += 2;
        foreach ($res as $k => $v) {
            $cate_name = '|--' . $v->name;
            $v->content = str_repeat('&nbsp;&nbsp;&nbsp;', $blank) . $cate_name;
            $result[] = $v;
            self::getInfinite($v->id, $result, $blank);
        }
        return Collection::make($result)->toArray();
    }
}

打印结果如下

^ array:7 [▼
  0 => array:4 [▼
    "id" => 1
    "pid" => 0
    "name" => "A一级"
    "content" => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|--Test"
  ]
  1 => array:4 [▼
    "id" => 2
    "pid" => 1
    "name" => "A二级"
    "content" => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|--Test"
  ]
  2 => array:4 [▼
    "id" => 3
    "pid" => 2
    "name" => "A三级"
    "content" => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|--Test"
  ]
  3 => array:4 [▼
    "id" => 4
    "pid" => 0
    "name" => "B一级"
    "content" => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|--Test"
  ]
  4 => array:4 [▼
    "id" => 5
    "pid" => 4
    "name" => "B二级"
    "content" => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|--Test"
  ]
  5 => array:4 [▼
    "id" => 6
    "pid" => 0
    "name" => "C一级"
    "content" => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|--Test"
  ]
  6 => array:4 [▼
    "id" => 7
    "pid" => 0
    "name" => "D一级"
    "content" => "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|--Test"
  ]
]

无限极分类其中的一种输出方式,主要用于新增菜单分类的选择等!!!

未完待续

猜你喜欢