php 列表转树结构

4 篇文章 0 订阅
<?php
 namespace app\common\library\utils;

/**
 * 列表转树结构
 */
class ListToTree {
 
    /**
     * 节点key
     */
    private $id = "id";
    // 父节点
    private $prent_id = "prent_id";
    // 层级
    private $level = "level";
    // 子级
    private $child = "child";
    // 列表
    private $list = [];
    // 树
    private $tree = [];
    
    // 单例模式
    private static $instance = null;
    private function __construct(){}
    private function __clone(){}
 
    /**
     * 实例化
     */
    public static function getInstance():self{
        if(self::$instance == null){
            self::$instance = new self();
        }
        return self::$instance;
    }
    /**
     * 设置节点
     */
    public function setConfig(string $id, string $prent_id ,string $level = "level", string $child ="child"):self
    {
        $this->id = $id;
        $this->prent_id = $prent_id;
        $this->level = $level;
        $this->child = $child;
        return $this;
    }
 
    /**
     * 设置列表
     */
    public function setList(array $list):self
    {
        $this->list = $list;
        return $this;
    }

    /**
     * 转成树
     */
    public function getTree():array
    {
        $this->tree = $this->toTree();
        return $this->tree;
    }

    /**
     * 转成树
     */
    private function toTree($pid = 0 , $level = 1):array
    {
        $tree = [];
        foreach ($this->list as $key => $value) {
            if($value[$this->prent_id] == $pid){
                $value[$this->level] = $level;
                $value[$this->child] = $this->toTree($value[$this->id] , $level ++);
                $tree[] = $value;
                unset($this->list[$key]);
            }
        }
        return $tree;
    }
 
 
    
}

 
// $commonList = [
//     [
//         'id' =>  1, 
//         'name' =>  '部门1', 
//         'pid' =>  0
//     ],
//     [
//         'id' =>  2, 
//         'name' =>  '部门2', 
//         'pid' =>  1
//     ],
//     [
//         'id' =>  3, 
//         'name' =>  '部门3', 
//         'pid' =>  1
//     ],
//     [
//         'id' =>  4, 
//         'name' =>  '部门4', 
//         'pid' =>  3
//     ],
//     [
//         'id' =>  5, 
//         'name' =>  '部门5', 
//         'pid' =>  4
//     ],
// ];
 
// ListToTree::getInstance()->setConfig('id','pid','level','child')->setList($commonList)->getTree();
  

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值