Tag Cloud Function

Blog, Code Snippets on February 17th, 2009 No Comments

Here is a simple function to render a tag cloud.  It assumes you have an array of data ready for it.  Also I originally built this for use with a stupid set of data where each entry has a space seperated list of tags like: “geek hotdogs snowboarding” so this function will also take all of those tags, parse them out, and then do all the good stuff. The function will make a cloud out of any data in your table. a Just specify the column name when you call the function. For example you could make a cloud based on users and the number of times they have posted.

Code:

	function tagCloud($column, $min_font_size = 15, $max_font_size = 40, $params = NULL) {
		$query = "SELECT $column FROM tweets $order";
		$tagresult = mysql_query($query);

		$tagmush = "";
		while ($tags = mysql_fetch_array($tagresult)) {
			$tagmush .= ' '.$tags[$column];
		}

		$tagarray = explode(" ", $tagmush);
		$countedtags = array_count_values($tagarray);	

		$minimum_count = min(array_values($countedtags));
		$maximum_count = max(array_values($countedtags));
		$spread = $maximum_count - $minimum_count;

		if($spread == 0) {
			$spread = 1;
		}
		$cloud_html = '';
		$cloud_tags = array(); // create an array to hold tag code
		foreach ($countedtags as $tag => $count) {
			$size = $min_font_size + ($count - $minimum_count)
				* ($max_font_size - $min_font_size) / $spread;

				// here is builds the html.  You should adjust as necessary
				$cloud_tags[] = ''
				. htmlspecialchars(stripslashes($tag)) . '';
		}
		$cloud_html = join("n", $cloud_tags) . "n";
		return $cloud_html;
	}

Usage:

// get the tag cloud for the user 'jake'
echo tagCloud("tags",15,40,"WHERE username = 'jake'");

Tags: , ,

No Responses to “Tag Cloud Function”

Leave a Reply

You must be logged in to post a comment.