<?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();