树遍历-如何排序结果?

时间:2018-11-15 14:05:08

标签: php sorting structure

我有一个简单的表格,可以通过Tree遍历分层地获取数据。

它工作得很好,但是现在我需要添加一个新功能。我需要按保存在数据库[rank]中新列中每一行的值每个级别中的数据进行排序。

我的桌子是:

+----+-----+-----+-------+--------+------------+------+
| ID | LFT | RGT | DEPTH | PARENT |   NAME     | RANK |
+----+-----+-----+-------+--------+------------+------+
|  1 |   1 |  22 |     0 |      0 | Category   |   10 |
|  2 |   2 |  15 |     1 |      1 | Fruit      |    8 |
|  3 |   3 |   8 |     2 |      2 | Apples     |    8 |
|  4 |   4 |   5 |     3 |      3 | Red        |    5 |
|  5 |   6 |   7 |     3 |      3 | Green      |    5 |
|  6 |   9 |  14 |     2 |      2 | Bannana    |    9 |
|  7 |  10 |  11 |     3 |      6 | Long       |    1 |
|  8 |  12 |  13 |     3 |      6 | Short      |    2 |
|  9 |  16 |  21 |     1 |      0 | Vegetables |    9 |
| 10 |  17 |  18 |     2 |      9 | Carrots    |    5 |
| 11 |  19 |  20 |     2 |      9 | Potatoes   |    6 |
| 12 |   8 |   9 |     3 |      3 | Yellow     |   10 |
+----+-----+-----+-------+--------+------------+------+ 

要列出我正在使用的脚本的结构:

$lftrgt  = mysql_fetch_assoc(mysql_query("SELECT name,lft,rgt,rank FROM myTable WHERE id='$id'"));
$result = mysql_query("SELECT * FROM myTable WHERE rgt < $lftrgt[rgt] AND lft > $lftrgt[lft] ORDER BY lft");
if(!$result) { echo mysql_error() . ' - ' . mysql_errno(); }
$depth = -1;
echo "<b><u>".$lftrgt[name] ." (rank: ". $lftrgt[rank] .")</u></b>";
while ($row = mysql_fetch_assoc($result)) {
if ($depth < $row["depth"]) {
echo "<ul>";
} else {
echo str_repeat("</li></ul>", $depth - $row["depth"]) . "</li>";
}
echo "<li>\n" . htmlspecialchars($row["name"]) ." (rank: " . $row[rank] . ")";
$depth = $row["depth"];
}
echo str_repeat("</li></ul>", $depth + 1) . "\n";
mysql_free_result($result); 

为了更好的主意,有我需要的图片:

screenshot

如何按降序对每个级别的结果进行排序?谢谢。

0 个答案:

没有答案