企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> ``` > public function treeBack($data,$pid){ > foreach($data as $k=>$v){ > if($v['pid'] == $pid){ > $v['child'] = $this->treeBack($data,$v['id']); > $tree[] = $v; > unset($data[$k]); > } > } > return $tree; > } > ``` - 如上代码,这是一段很经典的无限递归循环逻辑,但是当数据量超过2000 - 3000行时,效率大打折扣,经过我们的实际应用测试,在没有优化这段代码之前,递归所耗费的时间是 2s 左右 - 但是经过优化之后,递归逻辑耗费的时间仅仅只有 86ms 左右 - OK,贴出下优化后的代码再来分析 > ``` > public function treeBack($data, $pidKey='pid', $idKey = 'id', $childKey='child') { > $grouped = array(); > foreach ($flat as $sub){ > $grouped[$sub[$pidKey]][] = $sub; > } > $fnBuilder = function($siblings) use (&$fnBuilder, $grouped, $idKey, $childKey) { > foreach ($siblings as $k => $sibling) { > $id = $sibling[$idKey]; > if(isset($grouped[$id])) { > $sibling[$childKey] = $fnBuilder($grouped[$id]); > usort($sibling[$childKey], function($a, $b) use ($childKey) { > if ($a[$childKey] == $b[$childKey]) { > return 0; > } > return ($a['weight'] < $b['weight']) ? -1 : 1; > }); > } > $siblings[$k] = $sibling; > } > return $siblings; > }; > $tree = $fnBuilder($grouped[0]); > return $tree; > } > ``` - 恩,你没有看错,将数据重新构造,然后进行匿名函数循环