將標籤出現次數 (count) 映射到字體大小區間 [$minFontSize, $maxFontSize]:
size = minSize + (count - minCount) * (maxSize - minSize) / (maxCount - minCount)
<?php
/**
* 產生標籤雲 HTML
* @param array $tags ['tag' => count, ...]
* @param int $minSize 最小字體 (px)
* @param int $maxSize 最大字體 (px)
* @param string $urlTpl 連結模板,%s 會被標籤取代 (需 urlencode)
* @return string HTML 字串
*/
function tagCloud(array $tags, int $minSize = 12, int $maxSize = 30, string $urlTpl = '/tag/%s'): string
{
if (!$tags) return '';
$minCount = min($tags);
$maxCount = max($tags);
$spread = $maxCount - $minCount;
if ($spread === 0) $spread = 1; // 避免除零
$html = [];
foreach ($tags as $tag => $count) {
$size = $minSize + (($count - $minCount) * ($maxSize - $minSize) / $spread);
$size = round($size, 1);
$url = sprintf($urlTpl, urlencode($tag));
$title = htmlspecialchars("$tag (出現 $count 次)", ENT_QUOTES, 'UTF-8');
$tagHtml = htmlspecialchars($tag, ENT_QUOTES, 'UTF-8');
$html[] = "$tagHtml";
}
return implode(' ', $html);
}
// 使用範例
$tags = [
'PHP' => 120,
'Laravel' => 85,
'MySQL' => 70,
'Docker' => 60,
'Redis' => 55,
'Kubernetes' => 30,
'Git' => 25,
'CI/CD' => 20,
];
echo '<div class="tag-cloud">' . tagCloud($tags, 12, 36, '/search?q=%s') . '</div>';
.tag-cloud { line-height: 2.5; text-align: center; }
.tag-cloud-item {
display: inline-block;
margin: 0.2em 0.4em;
text-decoration: none;
color: #333;
transition: color 0.2s, transform 0.2s;
}
.tag-cloud-item:hover { color: #0066cc; transform: scale(1.1); }
function tagCloudLog(array $tags, int $minSize = 12, int $maxSize = 30): string
{
$maxCount = max($tags);
$logMax = log($maxCount + 1);
$html = [];
foreach ($tags as $tag => $count) {
$size = $minSize + (log($count + 1) / $logMax) * ($maxSize - $minSize);
// ... 同樣輸出
}
return implode(' ', $html);
}
對數縮放能讓低頻標籤不至於太小、高頻標籤不至於過大,視覺更平衡。
可搭配 TagCanvas (Canvas 3D 球狀旋轉) 或 d3-cloud (詞雲佈局) 做炫酷效果,後端只需輸出 JSON 陣列 [{text:'PHP', weight:120}, ...]。