我如何获取连接在多行值中的id的记录

问题描述 投票:1回答:1

下面是我的桌子

Id      User_id     type               content       item_id    secondary_item_id
   879       1         activity_comment   Amazing       833        833
   907       168       activity_comment   Great         833        879    
   908       1         activity_comment   Welcome       833        907 

我想输出评论回复结构,可以用一个例子来描述。在上表中,您可以看到user_id 1833 ( this is a post id )发表的评论,然后user 168对他的回复为“ Great”,然后再次对用户168进行user 1重播。

所以可能就像...

**MY POST** ( This is a post )

---- First comment( Amazing)
------- replay comment  (Great)
------------ sub replay (Welcome )

我已经编写了以下查询,但无法获得预期的输出。

SQL查询:

<?php 
  $listReplay =$wpdb->get_results("(SELECT * FROM table_one WHERE id = ".$value['secondary_item_id']."  AND type ='activity_comment') UNION DISTINCT 
                            (SELECT * FROM table_one WHERE secondary_item_id = ".$value['secondary_item_id']." AND type ='activity_comment')");
?>
php mysql sql arrays wordpress
1个回答
0
投票

首先让我们了解如何加载原始数据:

select Id, content, item_id, secondary_item_id
from table_one
where item_id = 833
order by item_id, secondary_item_id;

上面的查询将评论添加到帖子833上,并按帖子ID和父评论ID对其进行排序。到目前为止,一切都很好。现在,假设您已将原始数据存储在$rawResults中,则可以执行以下操作:

$map = [];
$parsedResults = [];
foreach ($rawResults as $rawResult) {
    if ($rawResult["secondary_item_id"] === $rawResult["item_id"]) {
        $parsedResults[$rawResult["Id"]] = [
            "content" => $rawResult["content"],
            "children" => []
        ];
        $map[$rawResult["Id"]] = $parsedResults[$rawResults["Id"]];
    } else {
        $map[$rawResult["secondary_item_id"]]["children"][$rawResult["Id"]]= [
            "content" => $rawResult["content"],
            "children" => []
        ]
    }
}

现在,您具有一个元素层次结构,主要级别是主要注释,可以在子项中找到答案。现在,您可以遍历分层数组,例如

function getComments($parsedResults, $prefix = "--- ") {
    $output = "";
    foreach ($parsedResults as $parsedResult) {
        $output .= $prefix.$parsedResult["content"]."\n";
        if (count($parsedResult["children"])) $output .= getComments($parsedResult["children"], "---".$prefix);
    }
    return $output;
}
© www.soinside.com 2019 - 2024. All rights reserved.