gpt4 book ai didi

php - 订购线程/嵌套评论 - PHP

转载 作者:行者123 更新时间:2023-12-02 05:26:39 26 4
gpt4 key购买 nike

我在网上找到了下面的线程评论示例,作者说这对他来说效果很好。但是,我在对结果进行排序时遇到问题,因此线程注释位于正确的位置。这是示例给我的内容:

Example author says: "I use a system which is simple and doesn't rely on recursion. I basically store the entire thread "path" as a row field. Want to get the entire tree structure? Just do an ORDER BY on the path column and use some PHP code like the following for formatting:"

示例数据

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

这是个大问题!这家伙是在胡说八道还是我做错了什么?除非数据的顺序与您要显示的顺序完全相同,否则它永远不会起作用。我可以做一些简单的事情来修复订单吗?

最佳答案

每个“主要”评论都必须有一个包含唯一 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 关系更适合这类事情。

关于php - 订购线程/嵌套评论 - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12982488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com