Everyone tells us how to create a tag cloud with an array.. but how to actually create the array with the data that we fetch from our database?
This is how I do it. The table we are working in is “pictures” and the field with the tags is “tags“. The tags are separated with a space (for example: sunset beautiful evening).
$query = mysql_query('select * from pictures where tags != "" group by tags');
while ($fetch = mysql_fetch_assoc($query)) {
$ex = explode(" ", $fetch['tags']);
$c = count($ex);
for ($i = 0; $i < $c; $i++) {
$tags[] .= $ex[$i];
}
}
What I do is fetch the data from all the fields named “tags” that are not empty. Then I separate the tags with the explode() function and I get an array. I count this array and I add every member of this array to my $tags array, which is the array that will include all the tags and which I’m going to use.
Then the usual code comes into play:
$c = array_count_values($tags); //count the array
$max_size = 32; //max size of the font in pixels
$min_size = 11; //min size of the font
$max_qty = max(array_values($c));
$min_qty = min(array_values($c));
$spread = $max_qty - $min_qty;
if ($spread == 0) {
$spread = 1;
}
$step = ($max_size - $min_size) / ($spread);
foreach ($c as $key => $value) {
$size = round($min_size + (($value - $min_qty) * $step)) . 'px';
$title = $value . ' pictures with the tag ' . $key;
echo '<span style="font-size: ' . $size . '" title="' . $title . '">' . $key . '</span> ';
}
This is it, all you need is a field in the table with the name tags and then you save your tags there, separated with a blank space.
If you have any questions feel free to ask, if you think I don’t know how to write in english please tell me and I will try harder
If you think this code sucks and have a better one please post it in the comments!