123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 |
- <?php
- namespace ba;
- class Tree
- {
-
- protected static $instance;
-
- public static $icon = array('│', '├', '└');
-
- protected $childrens = [];
-
- public static function instance(): Tree
- {
- if (is_null(self::$instance)) {
- self::$instance = new static();
- }
- return self::$instance;
- }
-
- public static function getTreeArray(array $arr, string $field = 'name', int $level = 0, bool $superiorEnd = false): array
- {
- $level++;
- $number = 1;
- $total = count($arr);
- foreach ($arr as $key => $item) {
- $prefix = ($number == $total) ? self::$icon[2] : self::$icon[1];
- if ($level == 2) {
- $arr[$key][$field] = str_pad('', 4) . $prefix . $item[$field];
- } elseif ($level >= 3) {
- $arr[$key][$field] = str_pad('', 4) . ($superiorEnd ? '' : self::$icon[0]) . str_pad('', ($level - 2) * 4) . $prefix . $item[$field];
- }
- if (isset($item['children']) && $item['children']) {
- $arr[$key]['children'] = self::getTreeArray($item['children'], $field, $level, $number == $total);
- }
- $number++;
- }
- return $arr;
- }
-
- public static function assembleTree(array $data): array
- {
- $arr = [];
- foreach ($data as $v) {
- $children = $v['children'] ?? [];
- unset($v['children']);
- $arr[] = $v;
- if ($children) {
- $arr = array_merge($arr, self::assembleTree($children));
- }
- }
- return $arr;
- }
-
- public function assembleChild(array $data, string $pid = 'pid', string $pk = 'id'): array
- {
- if (!$data) return [];
- $pks = [];
- $topLevelData = [];
- $this->childrens = [];
- foreach ($data as $item) {
- $pks[] = $item[$pk];
-
- $this->childrens[$item[$pid]][] = $item;
- }
-
- foreach ($data as $item) {
- if (!in_array($item[$pid], $pks)) {
- $topLevelData[] = $item;
- }
- }
- if (count($this->childrens) > 0) {
- foreach ($topLevelData as $key => $item) {
- $topLevelData[$key]['children'] = $this->getChildren($this->childrens[$item[$pk]] ?? [], $pk);
- }
- return $topLevelData;
- } else {
- return $data;
- }
- }
-
- protected function getChildren(array $data, string $pk = 'id'): array
- {
- if (!$data) return [];
- foreach ($data as $key => $item) {
- if (array_key_exists($item[$pk], $this->childrens)) {
- $data[$key]['children'] = $this->getChildren($this->childrens[$item[$pk]], $pk);
- }
- }
- return $data;
- }
- }
|