分类树服务 - 代码示例

buildTree() - 构建分类树
use app\common\service\CategoryTreeService; // 获取所有分类 $cats = getCat(0, 'product', 'cid asc'); $catArray = $cats->toArray(); // 构建树形结构 $tree = CategoryTreeService::buildTree($catArray, 0, 0); // 参数: $categories=分类数组, $parentId=父ID, $depth=深度 // 返回: 多维树形数组 // [ // ['cid'=>1, 'cnname'=>'分类1', 'depth'=>0, 'children'=>[ // ['cid'=>2, 'cnname'=>'子分类', 'depth'=>1, 'children'=>[]] // ]] // ]
getPath() - 获取分类路径
// 获取分类的完整路径 $path = CategoryTreeService::getPath($cats, $cid); // 返回: 从根到当前分类的路径数组 // 如: [根分类, 一级分类, 当前分类] // 用途: 面包屑导航
isValidCategoryId() - 验证分类ID
// 验证分类ID是否有效 $valid = CategoryTreeService::isValidCategoryId($cid); // 返回: true/false // 检查: 是否为正整数、是否存在于数据库 // 用途: 防止无效分类ID注入

buildTree() 树形结构

cid名称深度子分类数

getPath() 分类路径 (cid=2)

cid名称
--

isValidCategoryId() 验证

cid=2 是否有效: 是