feat(utils): 添加了快速无极分类的方法

Signed-off-by: 李东云 <dongyun.li@luxcreo.ai>
This commit is contained in:
李东云
2022-06-22 15:35:48 +08:00
parent 4e80d4ee67
commit a1537703f6

View File

@@ -2,8 +2,10 @@
namespace Singularity\HDK\Utils\Service;
use Closure;
use Exception;
use Generator;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Http\Message\ResponseInterface;
@@ -19,6 +21,12 @@ class UtilsService
*/
private RequestInterface $request;
/**
* @Inject()
* @var \Hyperf\Contract\StdoutLoggerInterface
*/
private StdoutLoggerInterface $logger;
/**
* 生成验证码
*
@@ -163,4 +171,53 @@ class UtilsService
fclose($file);
return $result;
}
/**
* level倒序快速无极分类时间复杂度 O(n),空间复杂度 O(1)
* 条件数组索引是数据parent_id对应的id只支持level倒序
*
* @param array $list
* @param int $level
* @param string $parentIdName
* @param string $childrenName
* @param \Closure|null $filterCallback
*
* @return void
*/
public function unlimitedSubCategoriesQuicklyWithLevel(
array &$list,
int $level = 1,
string $parentIdName = 'parent_id',
string $childrenName = 'children',
?Closure $filterCallback = null
): void {
$start_time = microtime(true);
$max_times = count($list);
$current_times = 0;
foreach ($list as $i => &$item) {
$current_times++;
if (!isset($item[$parentIdName])) {
break;
}
unset($list[$i]);
$item = isset($filterCallback) ? $filterCallback($item) : $item;
//判定非顶级的pid是否存在如果存在则再pid所在的数组下面加入一个字段items来将本身存进去
if (isset($list[$item[$parentIdName]])) {
$list[$item[$parentIdName]][$childrenName][] = $item;
continue;
}
//取出顶级
if ($item['level'] === $level) {
$list[$childrenName][] = $item;
}
}
$list = $list[$childrenName];
$end_time = microtime(true);
$this->logger->debug("快速无极分类循环{$current_times}次,数组元素数量$max_times");
$cost_time = ($end_time - $start_time) * 1000;
$this->logger->debug("快速无极分类用时{$cost_time}ms");
}
}