<?php
namespace laytp\library;
class Tree
{
protected static $instance;
public $map = [];
public $mapName = 'id';
public $pidName = 'pid';
public $childName = 'children';
public static function instance()
{
if (is_null(self::$instance)) {
self::$instance = new static();
}
return self::$instance;
}
public function init($arr = [])
{
$map = [];
foreach ($arr as &$it){
$map[$it['id']] = &$it;
}
$this->map = $map;
return $this;
}
public function getRootTrees()
{
$map = $this->map;
$res = [];
$rootTree = [];
foreach ($map as $id => &$item) {
$pid = &$item[$this->pidName];
if(!isset($map[$pid])){
$res[] = &$item;
}else{
$pItem = &$map[$pid];
$pItem[$this->childName][] = &$item;
}
}
if($res){
foreach($res as $k=>$value){
if($value[$this->pidName] == 0){
$rootTree[] = $value;
}
}
}
return $rootTree;
}
public function getTrees(){
$map = $this->map;
$res = [];
foreach ($map as $id => &$item) {
$pid = &$item[$this->pidName];
if(!isset($map[$pid])){
$res[] = &$item;
}else{
$pItem = &$map[$pid];
$pItem[$this->childName][] = &$item;
}
}
return $res;
}
public function getChildIds($ids, $withSelf=true){
$map = $this->map;
$res = [] if(!is_array($ids)){
$ids = explode(',', $ids);
$sourceIds = $ids;
}else{
$sourceIds = $ids;
}
$state = true;
while($state){
$otherIds = [];
foreach ($ids as $id) {
foreach ($map as $key => $value) {
if($value[$this->pidName] == $id){
$res[] = $value[$this->mapName] $otherIds[] = $value[$this->mapName] }
}
}
if(!$otherIds){
$state = false;
}else{
$ids = $otherIds }
}
if($withSelf){
foreach($sourceIds as $sId){
$res[] = intval($sId);
}
}
return $res;
}
public function getParentIds($ids, $withSelf=true){
$map = $this->map;
$res = [] if(!is_array($ids)){
$ids = explode(',', $ids);
$sourceIds = $ids;
}else{
$sourceIds = $ids;
}
$state = true;
while($state){
$otherIds = [];
foreach ($ids as $id) {
foreach ($map as $key => $value) {
if($value[$this->mapName] == $map[$id][$this->pidName]){
$res[] = $value[$this->mapName] $otherIds[] = $value[$this->mapName] }
}
}
if(!$otherIds){
$state = false;
}else{
$ids = $otherIds }
}
if($withSelf){
foreach($sourceIds as $sId){
$res[] = intval($sId);
}
}
return $res;
}
}