Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php无限极分类类(php 无限分类)

作者:农村混血兒   发布日期:2025-02-08   浏览:666

以下是一个简单的PHP无限极分类类示例:

class Category {
    private $categories;

    public function __construct() {
        $this->categories = array();
    }

    public function addCategory($id, $name, $parentId = 0) {
        $this->categories[$id] = array(
            'name' => $name,
            'parentId' => $parentId,
            'children' => array()
        );
    }

    public function buildTree($parentId = 0) {
        $tree = array();

        foreach ($this->categories as $categoryId => $category) {
            if ($category['parentId'] == $parentId) {
                $children = $this->buildTree($categoryId);
                if ($children) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }

        return $tree;
    }

    public function displayTree($tree, $level = 0) {
        foreach ($tree as $category) {
            echo str_repeat('-', $level) . $category['name'] . "<br>";
            if (!empty($category['children'])) {
                $this->displayTree($category['children'], $level + 1);
            }
        }
    }
}

// 示例用法
$categories = new Category();
$categories->addCategory(1, 'Category 1');
$categories->addCategory(2, 'Category 1.1', 1);
$categories->addCategory(3, 'Category 1.2', 1);
$categories->addCategory(4, 'Category 1.1.1', 2);
$categories->addCategory(5, 'Category 2');
$categories->addCategory(6, 'Category 2.1', 5);
$categories->addCategory(7, 'Category 2.1.1', 6);

$tree = $categories->buildTree();
$categories->displayTree($tree);

运行上述代码将输出以下结果:

Category 1
-Category 1.1
--Category 1.1.1
-Category 1.2
Category 2
-Category 2.1
--Category 2.1.1

这个示例演示了如何使用递归构建无限级分类树,并将其显示出来。在示例中,addCategory() 方法用于添加分类,buildTree() 方法用于构建分类树,displayTree() 方法用于显示分类树。

上一篇:php登录跳转到首页(php 登录页面)

下一篇:php如何禁止重定向(禁止重定向页面)

大家都在看

php session用法

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

php ||

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站