2012-10-19 156 views
2

我在网上找到了下面的线索评论示例,作者说这对他来说效果很好。但是,我在订购结果时遇到问题,因此线索评论在正确的位置。这就是例子给我:订购线程/嵌套注释 - PHP

例作者说:“我用的系统是简单的,不依赖于递归我 基本存储整个线程‘路径’作为行字段旺旺获得 整个树结构只是做一个ORDER BY上的路径列和 使用一些PHP代码像格式如下:?”

示例数据

ID | Comment      | Path 
---+------------------------------+---------- 
0 | Comment #1     | 00 
1 | Comment #1 reply    | 00_01 
2 | Comment #1 reply reply  | 00_01_02 
3 | Comment #2     | 00 
4 | Comment #3     | 00 
5 | Comment #3 reply    | 00_04 

的实例SQL

SELECT * FROM comments ORDER BY path 

的例子PHP

while ($result = mysql_fetch_assoc($query)) { 
    $nesting_depth = count(explode("_", $result['path'])); 
    $branch = str_repeat("--", $nesting_depth); 
    echo $branch {$result['comment']}"; 
} 

的例子结果

Comment #1 
-- Comment #1 reply 
---- Comment #1 reply reply 
Comment #2 
Comment #3 
-- Comment #3 reply 

我加入了精确的数据,以我的MySQL数据库和测试它并按预期工作。但是,如果我更改表中数据的顺序,则不起作用。我将解释:

REALISTIC测试数据

ID | Comment      | Path 
---+------------------------------+---------- 
0 | Comment #1     | 00 
1 | Comment #2     | 00 
2 | Comment #3     | 00 
3 | Comment #3 reply    | 00_04 
4 | Comment #1 reply    | 00_01 
5 | Comment #1 reply reply  | 00_01_02 

看看行[4]和行[5],这些回复意见中,加入最后的意见和彻底的改变了结果的顺序:

新的测试结果

Comment #1 
Comment #2 
Comment #3 
-- Comment #1 reply 
---- Comment #1 reply reply 
-- Comment #3 reply 

这是个大问题!这家伙说的是绝对的垃圾还是我做错了什么?除非数据的显示顺序完全相同,否则将无法使用。有没有简单的方法可以解决这个问题?

回答

3

每个“主要”注释都必须包含一个包含唯一ID号的路径。在你的情况下,每个“主要”评论的ID为00。如果你有三个,那么无法在两者之间得到答复。

ID | Comment      | Path 
---+------------------------------+---------- 
0 | Comment #1     | 00 
1 | Comment #2     | 00 
2 | Comment #3     | 00 
4 | Comment #1 reply    | 00_01 <-- Last item 

最后的item将一直是最后一项(按字母顺序)。如果您将每个“主要”评论与唯一ID区分开来,那么问题就解决了。

ID | Comment      | Path 
---+------------------------------+---------- 
0 | Comment #1     | 01 
1 | Comment #2     | 02 
2 | Comment #3     | 03 
4 | Comment #4 reply to 1 (1) | 01_01 <- first key is parent_id, second is sequence 
5 | Comment #5 reply to 1 (2) | 01_02 
6 | Comment #6 reply to 4 (1) | 04_01 
7 | Comment #7     | 04 
8 | Comment #8 reply reply to 5 | 01_02_01 

所以,当你要回复评论所有你需要做的是引用他们的整个路径,并在结尾处加上一个索引键。

在上表中:

01_01 = parent id: 01 -> sequence: 01 
04_01 = parent id: 04 (so a reply to id 4) -> sequence: 01 
01_02_01 = parent_id: 01_02 (references the path of ID 5) -> sequence: 01 

然后再次,这是一个怪异的结构。在我看来,id/parent_id关系对于这些事情更好。

+0

谢谢woo,解决了这个问题。这种构造将不得不现在做,但我会按照建议查找id/parent_id方法。 – ShadowStorm

2

构建的“路径”是垃圾。我在"00_04"(评论#3的回复)中看不到任何内容,它会告诉我此评论是评论#3的孩子。我想你会想要在你的路径中使用实际的ID号码作为评论。

ID | Comment      | Path 
---+------------------------------+---------- 
0 | Comment #1     | 00 
1 | Comment #2     | 01 
2 | Comment #3     | 02 
3 | Comment #3 reply    | 02_03 
4 | Comment #1 reply    | 00_04 
5 | Comment #1 reply reply  | 00_04_05