I have a database that, among other things, stores publications and publication tags. There is a many-to-many relationship between publications and publication tags. Simply put, I query the database for all the publication tags and the corresponding id. While looping through that query, I have a nested query to count the number of times each tag is used. Once I have all the information, I then loop through all results to display the tags. That seems inefficient, but I can't think of a better way. Thoughts?
//get the tag id and tag names
try {
$stmt = $pdo->prepare('SELECT publicationTagId, tagName FROM publicationTags WHERE EXISTS (SELECT publicationTags_publicationTagId FROM publications_have_publicationTags WHERE publicationTags_publicationTagId = publicationTagId)ORDER BY tagName');
$stmt->execute();
} catch(PDOException $e) {
echo "<p>Oops!</p>";
}
$tags = $stmt->fetchAll();
$tagCount = array();
//iterate through the tags and get usage counts
foreach($tags as $tag) {
try {
$stmt = $pdo->prepare('SELECT count(publicationTags_publicationTagId) FROM publications_have_publicationTags WHERE publicationTags_publicationTagId = :pubId');
$stmt->execute(array(':pubId'=>$tag[0]));
while($tagCounter = $stmt->fetch()) {
$tagCount[] = $tagCounter[0];
}
} catch(PDOException $e) {
echo "<p>Oops!</p>";
}
}
//get the min and max usages
$minUse = min($tagCount);
$maxUse = max($tagCount);
//max and min font size
$maxPercent = 150;
$minPercent = 100;
//prevent divide by zero
$divisor = ($maxUse == $minUse) ? 1 : $maxUse - $minUse;
//multiplier
$multiplier = ($maxPercent - $minPercent) / $divisor;
//set up list
echo "<ul class='tagCloudList'>";
$counter = 0;
//loop through tags
foreach($tags as $tag) {
$size = $minPercent + ($tagCount[$counter][0]-$minUse)*$multiplier;
echo "<li><a href='?pubTag=$tag[1]' style='font-size:$size%'>$tag[1]</a></li>";
$counter++;
}
//reset link
echo "<li><a href='publications.php'>View All</a></li>";
//close the list
echo "</ul>";