如何在PHP中创建哈希列表?

如何在PHP中创建哈希列表?,php,mysql,Php,Mysql,如何在PHP中创建标签列表 我有一张“posts”表 此表包含3个字段(id、文本、哈希) 像这样的数据 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

如何在PHP中创建标签列表

我有一张“posts”表

此表包含3个字段(id、文本、哈希)

像这样的数据

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

您的代码中有什么不起作用?您不需要这样的设置。您应该有这样的设置:
posts(id,text)
标记(id,tag)
,以及
关系(id,post\u id,tag\u id)
。然后,您可以按
tag\u id DESC
关系表进行排序,并提取最常用的前3个。如果
tags
表只存储不必要的代理主键,而不存储任何信息,那么就没有理由使用它。
relationships
表也不需要
id
post_id,tag
本身就是主键。似乎你已经养成了一个习惯,在每个表中添加一个
id
列,即使它不需要。是的,你是对的。但是,如果程序员打算最终存储更多的数据而不仅仅是一个标记名,那么使用表可能是有意义的,例如,如果他/她将标记与其他信息相关联。您还可以在
标记
表中有一个名为
计数
的列,该列会定期更新(或者每当添加/更新帖子时,其频率可能低于访问顶部散列),这可能会加快查询速度?不确定。我试过了

`
<?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
-->