2013-08-02 2 views
0

Как я могу сделать верхний список hashtag в PHP?Как я могу сделать хеш-лист в PHP?

У меня есть таблица "сообщения"

Эта таблица содержит 3 поля (идентификатор, текст, хэш)

данные как этот

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 
+0

Что не работает в вашем коде? – user20232359723568423357842364

+5

Вам не нужна настройка, подобная этой. У вас должна быть такая настройка: 'posts (id, text)', 'tags (id, tag)' и 'relationship (id, post_id, tag_id)'. Затем вы можете сортировать таблицу 'relations' с помощью' tag_id DESC' и вытаскивать верхние 3 наиболее используемые. –

+1

Нет никакой причины для таблицы «тегов», когда она не хранит никакой информации, кроме ненужного первичного ключа суррогата. Столбец 'relations' также не нужен столбец' id'; 'post_id, tag' является первичным ключом самостоятельно. Кажется, у вас сложилась привычка добавлять столбец «id» к каждой таблице, даже если она не нужна. –

ответ

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

Дайте мне знать, если вам нужна помощь в этом. Неподтвержденный код, поэтому не уверен, работает он или нет.

Смежные вопросы