How to perform unlimited classification based on id and pid
擁有18年軟件開發(fā)和IT教學(xué)經(jīng)驗(yàn)。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項(xiàng)目經(jīng)理、高級(jí)軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
Use a recursive function, but the space complexity of this method was not optimized. I forgot the previous way of writing it
private function getTreeList($data, $pid = 0)
{
$resultarr = array();
foreach ($data as $teamdata) {
if ($teamdata['pid'] == $pid) {
$team_data = $teamdata;
$children_data = $this->getTreeList($data, $teamdata['id']);
$team_data['children'] = $children_data;
$resultarr[] = $team_data;
}
}
return $resultarr;
}
public function gettree($items, $parent_id = 'parent_id', $id = 'id'){
$tree = array(); //格式化好的樹
if(empty($items)){
return $tree;
}
foreach ($items as $item){
if (isset($items[$item[$parent_id]])){
$items[$item[$parent_id]]['son'][] = &$items[$item[$id]];
}else{
$tree[] = &$items[$item[$id]];
}
}
return $tree;
}