开发者

Adding, removing and updating tags for comments in web page

I'm building a commenting feature for a web page where all comments can have any number of tags (not HTML tags, but tags like here in SO, duplicates not allowed) and those tags can be updated by anybody.

Let's say some comment contains tags [tag1, tag2, tag3] and someone adds one tag, tag4, removes tag2. Now how do I check that which old tag was not in the new set of tags, and what tags were possibly added?

I have table comments, which contains id and comment columns (among others, not related to this problem) and comment_tags table, which have id, tag and comment_id columns.

I could get all old tags to given comment, then loop through that array and with each tag, check that was that included in the new set of tags. If not, delete that tag. And then loop through the new set of tags, check with each new tag that is it included in the old set of tags. If not, add that tag to comment_tags table.

Somehow that just sounds too slow and I'm guessing that there is some better way to do that. So this was my initial thought:

$db = new Database();
$purifier = new HTMLPurifier();

$existing_tags = $db -> get_comment_tags($_POST['comment_id']);

$new_tags = $purifier -> purify($_POST['tags']);
$new_tags = explode(" ", $new_tags);
$new_tags = array_unique($new_tags);

/* De开发者_如何学Pythonlete tags that were not included in the new set of tags */
foreach ($existing_tags as $tags => $tag) {
    if (!in_array($tag['tag'], $new_tags)) {
        $db -> delete_comment_tag($existing_tags[$tags]['id']);
    }
}

/* Since get_comment_tags returns array which contains arrays, 
let's strip unnecessary info */
$filtered_existing_tags = array();
foreach ($existing_tags as $key => $value) {
    $filtered_existing_tags[] = $value['tag'];
}

/* Add tags that were not included in the old set of tags */
foreach ($new_tags as $key => $value) {
    if (!in_array($value, $filtered_existing_tags)) {
        $db -> add_comment_tag($_POST['comment_id'], $value);
    }       
}


I usually would just run two SQL queries to accomplish that, both on the posts_tags table: one to delete all tags currently linked to the post, and another one to insert all currently valid tags.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜