技术文摘
PHP无限分级类的打造(含完整代码及注释)
2025-01-02 02:35:00 小编
PHP无限分级类的打造(含完整代码及注释)
在PHP开发中,无限分级是一个常见的需求,比如构建分类目录、评论回复等。下面我们来打造一个PHP无限分级类,实现灵活的分级管理。
我们创建一个名为Category的类。这个类用于表示一个分类,包含属性如id(分类ID)、name(分类名称)、parent_id(父分类ID)和children(子分类数组)。
class Category {
public $id;
public $name;
public $parent_id;
public $children = [];
public function __construct($id, $name, $parent_id) {
$this->id = $id;
$this->name = $name;
$this->parent_id = $parent_id;
}
}
接下来,我们创建一个CategoryTree类来管理分类树。它有一个$categories数组用于存储所有分类,以及方法addCategory用于添加分类和buildTree用于构建分类树。
class CategoryTree {
private $categories = [];
public function addCategory(Category $category) {
$this->categories[] = $category;
}
public function buildTree() {
$tree = [];
foreach ($this->categories as $category) {
if ($category->parent_id == 0) {
$tree[] = $category;
} else {
$parent = $this->findParent($category->parent_id);
if ($parent) {
$parent->children[] = $category;
}
}
}
return $tree;
}
private function findParent($parent_id) {
foreach ($this->categories as $category) {
if ($category->id == $parent_id) {
return $category;
}
}
return null;
}
}
使用这个无限分级类很简单,我们可以创建分类实例,添加到CategoryTree中,然后构建分类树。
$tree = new CategoryTree();
$category1 = new Category(1, '一级分类1', 0);
$category2 = new Category(2, '二级分类1', 1);
$tree->addCategory($category1);
$tree->addCategory($category2);
$categoryTree = $tree->buildTree();
通过这个PHP无限分级类,我们可以方便地管理和操作具有无限层级关系的数据,为各种分级应用提供了强大的支持。
- 老码农的编程秘籍:10 个技巧与 5 个纠错步骤助你铺平编程之路
- 怎样使 Pandas 迭代速度提升 150 倍
- 程序员的外包经历:印度、中国与菲律宾
- 神秘的并发可见性
- 一行代码安装,TPU 支持运行 PyTorch,少量代码修改实现快速移植
- 10 行代码实现目标检测的方法
- 如何实现软件架构的传承
- 微盟灾难过后放弃自建数据库 赔付商家 1.5 亿
- 读懂 Docker 容器技术架构与各模块
- 面试官:谈谈你对 SpringAOP 的了解?掌握这些内容,绝对加分!
- Python 可视化库全面盘点,是否有你心仪的?
- K8S 集群入门:运行应用程序所需集群数量探究
- 《代码整洁之道》的 5 大要点
- 命令行揭示:Fuchsia 迈入 dogfood 测试阶段
- 谷歌新发布 2500 万个免费数据集,速览!