Tag Archives: PHP

My darling web scripting language.

Building a Tag Cloud (logic)

Once we have the data we want, we can build the logic to make the cloud.
Here the logic is extremely simple (no wonder I’ve made a tutorial about it).

The idea is to assign a minimum font-size in “pt” to the least occured tag. In our case we have taken 8pt. Since this 8pt size is applicable to the XML tag (our example), whose tag count is 3. We need to find a multiplying factor for all the tags, that will give us their respective font sizes.

The multiplying factor should take into account, the tags count, and the total of the tag count, which in turn is the percentage of occurance for that tag. So if the factor is x, tag count is 3, tag count sum is 58 and font size is 8, the equation would be

(3 / 58) * x = 8
which gives us x as 
x = (58 / 3) * 8

Now this x has to be multiplied to the % factor of that tag,
to get it's font size value

tag[http] = (10 / 58) * ( (58 / 3) * 8 )

so lets go with PHP,

$min_val = min($tags);
$font_multiplier = ($tag_sum / $min_val) * 8;

// assign the the font sizes
foreach($tags as $key => $value) {
  $tags[$key] = ($value / $tag_sum) * $font_multiplier;
}

Now is the time to display the tags, and link it to what ever, The spacing for each tag word would be fixed I’ll keep it 15pt. Its upto your design to change it!

foreach($tags as $key=>$value) {
  echo "<span style='font-size: {$value}pt; font-family: 
        tahoma;'>$key</span><span style='font-size: 15pt; font-family: 
        tahoma;'>  </span>";
}

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;