function 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 - 26 2 - 13 - 14 - 24 3 - 10 - 18 - 19 - 20 4 5 - 12 - 21 - 22 - 23 6 7 - 15 - 16 - 17 SHOULD BE: 1 - 8 - 9 - 11 - 25 - 26 2 - 13 - 14 - 24 3 - 10 - 18 - 19 - 20 4 5 - 12 - 21 - 22 - 23 6 7 - 15 - 16 - 17