<?php
namespace App\Helpers;
// 生成树状结构数据处理类
class Tree
{
// 存储数据
private $lists = [];
// 主键ID
public $primaryKey = NULL;
// 父级字段名
public $parentKey = NULL;
// 存储子节点的键名
public $childrenKey = NULL;
// 数据初始化
public function __construct($primaryKey = '',$parentKey = '',$childrenKey = '',$data = [])
{
if (empty($primaryKey) || empty($parentKey) || empty($childrenKey) || empty($data)) return '参数不能为空';
$this->primaryKey = $primaryKey;
$this->parentKey = $parentKey;
$this->childrenKey = $childrenKey;
$this->lists = $data;
}
// 获取树状数据
public function getTree($root = 0)
{
if (!is_array($this->lists)) return '数据源必须为数组';
// 最终树形结构数据
$tree = [];
// 存储主键与数组单元的引用关系
$refer = [];
// 组合引用关系
foreach($this->lists as $k => $v){
if(!isset($v[$this->primaryKey]) || !isset($v[$this->parentKey]) || isset($v[$this->childrenKey])){
unset($this->lists[$k]);
continue;
}
// 为每个数组成员建立引用关系
$refer[$v[$this->primaryKey]] = &$this->lists[$k];
}
unset($k);
unset($v);
// 组合树形数据
foreach($this->lists as $k => $v){
if ($v[$this->parentKey] == $root) { // 根分类直接添加引用到tree中
$tree[] = &$this->lists[$k];
} else {
if (isset($refer[$v[$this->parentKey]])) {
$parent = &$refer[$v[$this->parentKey]]; // 获取父分类的引用
$parent[$this->childrenKey][] = &$this->lists[$k]; // 在父分类的children中再添加一个引用成员
}
}
}
return $tree;
}
}