rendered paste bodyfunction showTree($index=0, $tree, $depth=0){ foreach($tree as $key => $value) { $key = explode("_", $key); $thisid = $key[1]; $this_parent = $key[0]; if($this_parent == $index) { echo str_repeat(" ", $depth).(($depth==0) ? "" : " - ").$thisid."\n"; showTree($thisid, $tree, $depth); } else $depth++; }}function buildCategoryTree(){ global $mysql; $categories = $mysql->query("SELECT * FROM `categories`"); while($row = $categories->fetchArray()) { $tree[$row['parent_id']."_".$row['id']] = $row['name']; } return $tree;}showTree(0, buildCategoryTree(), 0);OUTPUT:1 - 8 - 9 - 11 - 25 - 262 - 13 - 14 - 243 - 10 - 18 - 19 - 2045 - 12 - 21 - 22 - 2367 - 15 - 16 - 17SHOULD BE:1 - 8 - 9 - 11 - 25 - 262 - 13 - 14 - 243 - 10 - 18 - 19 - 2045 - 12 - 21 - 22 - 2367 - 15 - 16 - 17