gpt4 book ai didi

php - 如何在 PHP 中创建哈希顶部列表?

转载 作者:行者123 更新时间:2023-11-30 01:25:39 25 4
gpt4 key购买 nike

如何在 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

最佳答案

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

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

关于php - 如何在 PHP 中创建哈希顶部列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18025546/

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