php递归方法实现无限分类实例代码



<?php

class Category {
    public $id;
    public $name;
    public $parentId;
    public $children = [];

    public function __construct($id, $name, $parentId) {
        $this->id = $id;
        $this->name = $name;
        $this->parentId = $parentId;
    }

    // 递归构建分类树
    public static function buildTree($categories, $parentId = 0) {
        $branch = array();

        foreach ($categories as $category) {
            if ($category->parentId == $parentId) {
                $children = self::buildTree($categories, $category->id);
                if ($children) {
                    $category->children = $children;
                }
                $branch[] = $category;
            }
        }

        return $branch;
    }

    // 示例数据
    public static function getSampleData() {
        return [
            new Category(1, 'Electronics', 0),
            new Category(2, 'Televisions', 1),
            new Category(3, 'Portable Electronics', 1),
            new Category(4, 'MP3 Players', 3),
            new Category(5, 'Flash Memory', 3),
            new Category(6, 'Books', 0),
            new Category(7, 'Authors', 6),
            new Category(8, 'Fiction', 6),
            new Category(9, 'Science Fiction', 8),
            new Category(10, 'Fantasy', 8),
        ];
    }

    // 示例用法
    public static function exampleUsage() {
        $categories = self::getSampleData();
        $tree = self::buildTree($categories);

        // 打印分类树(简单示例)
        self::printTree($tree, 0);
    }

    // 递归打印分类树
    public static function printTree($tree, $level = 0) {
        foreach ($tree as $category) {
            echo str_repeat('----', $level) . $category->name . "\n";
            if (!empty($category->children)) {
                self::printTree($category->children, $level + 1);
            }
        }
    }
}

// 调用示例
Category::exampleUsage();

这段代码定义了一个`Category`类,用于表示分类。它包含了递归方法`buildTree`来构建一个分类树,其中每个分类可以有多个子分类。`getSampleData`方法提供了一个示例分类数据集合,而`exampleUsage`方法则展示了如何使用`buildTree`方法来构建并打印分类树。`printTree`方法用于递归地打印分类树,以便于查看结果。