I have a database table with parent-children rows, one parent-many children, linked by field "parent".
I know how to loop and print a jerarquy structure by using recursive function in PHP, but when I try to reproduce it with a single loop code, I cannot present the data in the same format. This sample of code lists all items in the database table, but not ordered, it prints first the top level, and I want the classical:
Top 1 >> Level 1 >> Level 2 >> Level 3
Top 2 >> Level 1
Top 3 >> Level 1 >> Level 2
$parent = array();
array_push($parent, 0);
while(!empty($parent)){
foreach($parent as $key => $mother){
unset($parent[$key]);
$sql = "SELECT * FROM levels WHERE parent = " . $mother;
$res = mysql_query($sql);
while($row=mysqli_fetch_object($res)){
print $row->name . "<br />";
array_push($parent, $row->id);
} // while
} // foreach
} // while
The result of this code is
Top 1 Top 2 Top 3 Level 1 ...