2010-11-14 6 views
1

J'ai donc une table et les colonnes sont id, parent-id et name.Tri des entrées MySQL en tant qu'enfant et parent

Voici ce qui se passe.

1 Web Design 
- 5 Templates 
- 6 Finished Websites 
2 Graphic Design 
3 Photography 
4 Image Manipulation 

de ceci:

while($row = mysql_fetch_array($result)) { 
echo $row['id'] . " "; 
echo $row['name'] . "<br/ >"; 

while($row = mysql_fetch_array($result2)) { 
    echo "- " . $row['id'] . " "; 
    echo $row['name'] . "<br/ >"; 
} 
} 

Comment puis-je lister dynamiquement tous childern sous leurs parents respectifs tels que ...

1 Web Design 
- 5 Templates 
- 6 Finished Websites 
2 Graphic Design 
- 7 T-Shirts 
- 8 Logos 
3 Photography 
- 9 Portraits 
- 10 Nature 
- 11 Animal 
- 12 Architecture 
4 Image Manipulation 

Répondre

1

Nevermind got it ....

// Get all the data from the "example" table 
$result = mysql_query("SELECT * FROM `portfolio-categories` WHERE `parent-id` ='0'") 
or die(mysql_error()); 

// keeps getting the next row until there are no more to get 

$parent = 0; 

while($row = mysql_fetch_array($result)) { 
    echo $row['id'] . " "; 
    echo $row['name']; 

    $parent += 1; 
    echo "#" . $parent . "#"; 

    echo "<br/ >"; 

    $result2 = mysql_query("SELECT * FROM `portfolio-categories` WHERE `parent-id`=$parent") 
or die(mysql_error()); 

    while($row = mysql_fetch_array($result2)) { 
     echo "- " . $row['id'] . " "; 
     echo $row['name'] . "<br/ >"; 
    } 
} 
0
 
function items($parent_id) 
{ 
    $query = "SELECT * FROM mytable WHERE parent_id = $parent_id" 

    $result = mysql_fetch_array(mysql_query($query)) 

    foreach ($result as &$res) 
    { 
     echo $res['id'] . " "; 
     echo $res['name'] . ""; 
     echo items($parent_id) 
    } 
} 
Questions connexes