2019-12-11 20:59:59 +08:00
|
|
|
<?php
|
2020-11-29 09:29:14 +08:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2019-12-12 09:14:08 +08:00
|
|
|
namespace catcher;
|
|
|
|
|
|
|
|
class Tree
|
|
|
|
{
|
2021-05-25 08:28:19 +08:00
|
|
|
protected static $pk = 'id';
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @author CatchAdmin
|
|
|
|
* @time 2021年05月25日
|
|
|
|
* @param array $items
|
|
|
|
* @param int $pid
|
|
|
|
* @param string $pidField
|
|
|
|
* @param string $children
|
|
|
|
* @return array
|
|
|
|
*/
|
|
|
|
public static function done(array $items, $pid = 0, $pidField = 'parent_id', $children = 'children'): array
|
2019-12-12 09:14:08 +08:00
|
|
|
{
|
|
|
|
$tree = [];
|
|
|
|
|
2021-05-25 08:28:19 +08:00
|
|
|
foreach ($items as $item) {
|
2019-12-12 09:14:08 +08:00
|
|
|
if ($item[$pidField] == $pid) {
|
2021-05-25 08:28:19 +08:00
|
|
|
$child = self::done($items, $item[self::$pk], $pidField);
|
2019-12-26 09:03:19 +08:00
|
|
|
if (count($child)) {
|
|
|
|
$item[$children] = $child;
|
|
|
|
}
|
2019-12-12 09:14:08 +08:00
|
|
|
$tree[] = $item;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $tree;
|
|
|
|
}
|
|
|
|
|
2021-05-25 08:28:19 +08:00
|
|
|
/**
|
|
|
|
* set pk field
|
|
|
|
*
|
|
|
|
* @author CatchAdmin
|
|
|
|
* @time 2021年05月25日
|
|
|
|
* @param string $pk
|
|
|
|
* @return $this
|
|
|
|
*/
|
|
|
|
public static function setPk(string $pk): Tree
|
|
|
|
{
|
|
|
|
self::$pk = $pk;
|
|
|
|
|
|
|
|
return new self;
|
|
|
|
}
|
2019-12-12 09:14:08 +08:00
|
|
|
|
|
|
|
}
|