php与css 标签云效果

发布时间:2020-12-22编辑:脚本学堂
本文介绍下,php与css、mysql一起实现的一个标签云的效果,有需要的朋友,可以作个参考。

以下代码,实现一个标签云的效果。
只给出核心代码,供大家学习参考。

1,创建标签云的函数
 

复制代码 代码示例:
function createTagCloud($tags) 
{    
    //I pass through an array of tags 
    $i=0; 
    foreach($tags as $tag) 
    { 
        $id = $tag['id']; //the tag id, passed through 
        $name = $tag['tag']; //the tag name, also passed through in the array 
         
        //using the mysql count command to sum up the tutorials tagged with that id 
        $sql = "SELECT COUNT(*) AS totalnum FROM tutorials WHERE tags LIKE '%".$id."%' AND published = 1"; 
         
        //create the resultset and return it 
        $res = mysql_query($sql); 
        $res = mysql_fetch_assoc($res); 
         
        //check there are results ;) 
        if($res) 
        { 
            //build an output array, with the tag-name and the number of results 
            $output[$i]['tag'] = $name;  
            $output[$i]['num'] = $res['totalnum']; 
        } 
         
        $i++; 
    } 
     
    /*this is just calling another function that does a similar SQL statement, but returns how many pieces of content I have*/ 
    $total_tuts = $this->getNumberOfTutorials(); 
     
    //ugh, XHTML in PHP?  Slap my hands - this isn't best practice, but I was obviously feeling lazy 
    $html = '<ul class="tagcloud">'; 
     
    //iterate through each item in the $output array (created above) 
    foreach($output as $tag) 
    { 
        //get the number-of-tag-occurances as a percentage of the overall number 
        $ratio = (100 / $total_tuts) * $tag['num']; 
         
        //round the number to the nearest 10 
        $ratio =  round($ratio,-1); 
         
        /*append that classname onto the list-item, so if the result was 20%, it comes out as cloud-20*/ 
        $html.= '<li class="cloud-'.$ratio.'"><a href="/tag/'.$tag['tag'].'">'.$tag['tag'].'</a></li>';          
    } 
     
    //close the UL 
    $html.= '</ul>'; 
     
    return $html;  

2,css代码部分
/*删除默认的列表样式,使之成为一个普通的清单列表*/ 
 

复制代码 代码示例:
.home-item ul.tagcloud 

    list-style-type:none; 
    margin:0px; 
    padding:0px; 

 
/*设置li的样式*/ 
.home-item ul.tagcloud li 

    display:inline !important; 
    margin-right:15px; 
    line-height:2em; 

 
.home-item ul.tagcloud li a 

    display:inline; 

 
/*标签云的效果*/ 
.home-item ul.tagcloud li.cloud-10 a 

    font-size:110%; 

 
.home-item ul.tagcloud li.cloud-20 a 

    font-size:120%; 

 
.home-item ul.tagcloud li.cloud-30 a 

    font-size:130%; 

 
/************************************* 
you get the idea, i'm skipping a few 
*************************************/ 
 
.home-item ul.tagcloud li.cloud-90 a 

    font-size:190%; 

 
.home-item ul.tagcloud li.cloud-100 a 

    font-size:200%;