1

如何在 PHP 中制作主题标签顶部列表?

我有一张“帖子”表

该表包含 3 个字段(id、text、hash)

像这样的数据

id   => 1
text => i'm from #us
hash => ,us

id   => 2
text => i #love #us
hash => ,love ,us 

id   => 3
text => i will travel to #us cus i #love it
hash => ,us ,love

id   => 4
text => i will go to #us #now 
hash => ,us ,now

我想显示这样的数据

顶部哈希

us
love
now
4

1 回答 1

0
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
    // A MySQLi connection

/* Database setup:
`posts`
    `id`
    `text`

`tags`
    `tag`
    `post_id`
*/

function add_post ($text, $tags = array ()) {
    global $sql;

    $sql->query('INSERT INTO `posts` (`text`) VALUES ("'.$sql->real_escape_string($text).'");');
        // Insert the post into the posts table
    $postID = $sql->insert_id;
        // Capture its id

    if (count($tags) != 0) {
        foreach ($tags as &$tag) {
            $tag = $sql->real_escape_string($tag);
        }
        unset($tag);
            // Escape every tag

        $sql->query('INSERT INTO `tags` (`tag`, `post_id`) VALUES ("'.implode('", '.$postID.'), ("', $tags).'", '.$postID.');');
            // Insert the tags associated with this post as records in the tags table
    }
}

// If/when you write update_post and delete_post functions, you will need to manage the tags associated with them as well
// Probably it's best to use a relational system like InnoDB

function get_top_tags ($num = 3) {
    global $sql;

    $result = $sql->query('SELECT `tag`, COUNT(`tag`) AS `frequency` FROM `tags` GROUP BY `tag` ORDER BY `frequency` DESC LIMIT '.(int) $num.';');
        // Get the tags in order of most to least frequent, limited to $num

    $tags = array ();
    while ($row = $result->fetch_assoc()) {
        $tags[] = $row['tag'];
    }
        // Turn them into an array
    return $tags;
}

// Example usage:
add_post('This is a new post.', array ('this', 'post', 'new'));
add_post('This is an old post.', array ('this', 'post'));
add_post('That is a medium-aged post.', array ('post'));
?>
<h1>Top Tags</h1>
<ol>
<?php
foreach (get_top_tags(3) as $tag) {
?>
    <li><?php echo $tag; ?></li>
<?php
}
?>
</ol>
<!-- Should print
1. post
2. this
3. new
-->

如果您需要帮助,请告诉我。未经测试的代码,所以不确定它是否有效。

于 2013-08-02T21:01:30.870 回答