<? php $stime = microtime(true); $nodes = [ ['id' = > 1, 'pid' = > 0, 'name' = > 'a'], ['id' = > 2, 'pid' = > 0, 'name' = > 'b'], ['id' = > 3, 'pid' = > 1, 'name' = > 'c'], ['id' = > 4, 'pid' = > 2, 'name' = > 'd'], ['id' = > 5, 'pid' = > 6, 'name' = > 'e'], ['id' = > 6, 'pid' = > 4, 'name' = > 'f'], ['id' = > 7, 'pid' = > 6, 'name' = > 'g'], ['id' = > 8, 'pid' = > 6, 'name' = > 'h'], ['id' = > 9, 'pid' = > 10, 'name' = > 'i'], ['id' = > 10, 'pid' = > 8, 'name' = > 'j'] ]; function tree($list, $id = 'id', $pid = 'pid', $name = 'name') { $data = []; foreach($list as $row) { $data[$row[$id]][$name] = $row[$name]; $data[$row[$pid]]['children'][$row[$id]] = & $data[$row[$id]]; } return isset($data[0]['children']) ? $data[0]['children'] : []; } print_r(tree($nodes)); $etime = microtime(true); echo '运行后内存:'.round(memory_get_usage() / 1024 / 1024, 2). 'MB '; $total = $etime - $stime; //计算差值 echo "[页面执行时间:{$total} ]秒"; ?>