Building a Tag Cloud

You may have come across Del.icio.us Tags, which is commonly referered as a “Tag cloud”
tag cloud

It is extremely easy to build such a cloud, all you need to have is to have tags associated with your posts, comments, blogs, etc.

Consider you have a table of posts called POSTS, and another one of TAGS, something like below.

posts
* post_id
* tag_id
* post_content

tags
* tag_id
* tag_name

We need to get the count of tags, and the no. of times that tag has been associated. The query would be.

select a.tag_name, count(b.post_id) tag_count
from tags a, posts b
where a.tag_id = b.tag_id
group by b.tag_id
order by a.tag_name

This will give us a result like this

AJAX, 15
HTTP, 10
Web, 30
XML, 3

Let us decide a minimum font size for the tag, let us take the value of 8pt as the smallest font possible, All that remains is to calculate the font sizes.

We’ll grab the result set first and get the sum of tag count.

$tags = array();
$tag_sum = 0;
while ($row = mysql_fetch_object($res)) {
  $tags[$row->tag_name] = $row->tag_count;
  $tag_sum = $tag_sum + $row->tag_count;
}

// just make a copy of the tags array
$tags_copy = $tags;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.