将MySQL条目排序为子级和父级

时间:2010-11-14 08:17:56

标签: mysql parent-child

所以我有一个表,列是id,parent-id和name。

出现了什么。

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

来自:

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/ >";
 }
}

如何动态列出各自父母的所有孩子,例如......

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

2 个答案:

答案 0 :(得分:1)

没关系,明白了......

// 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/ >";
    }
}

答案 1 :(得分: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)
    }
}