Fork me on Baidu

构建树和给对应的分类 拼接字符串 (无限极分类)

<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class CategoryServe extends Model
{
    // 表名
    protected $name = 'category_serve';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'parent_name'
    ];

    public function getParentNameAttr($value, $data)
    {
        $result = Db::name('category_serve')->select();
        $list = collection($result)->toArray();
        $get_deal_data = $this->buildTree($list);
        $categoryNameWithLevel = $this->findCategoryByNameAndLevel($get_deal_data, $data['id']);
        return $categoryNameWithLevel;
    }

    private function findCategoryByNameAndLevel(array $categories, int $id, string $parentNames = ''): string
    {
        foreach ($categories as $category) {
            if ($category['id'] == $id) {
                return $parentNames . str_repeat('==', $category['level']) . $category['name'];
            }
            if (!empty($category['children'])) {
                $newParentNames = $parentNames . str_repeat('==', $category['level']) . $category['name'] . ' > ';
                $result = $this->findCategoryByNameAndLevel($category['children'], $id, $newParentNames);
                if ($result) {
                    return $result;
                }
            }
        }
        return '';
    }
    private function buildTree(array $categories, int $parentId = 0, int $level = 0): array
    {
        $tree = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                // 添加层级信息
                $category['level'] = $level;
                // 递归查找子分类
                $children = $this->buildTree($categories, $category['id'], $level + 1);
                if ($children) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }
        return $tree;
    }
}

  

 

posted @ 2025-03-01 17:24  consideration  阅读(7)  评论(0)    收藏  举报