這里來介紹PHP將頁面中點擊數(shù)量高的鏈接進(jìn)行高亮顯示的方法,主要受到WordPress中某插件的啟發(fā),需要的朋友可以參考下
背景和需求
就好比說頁面導(dǎo)航的左側(cè)是分類,分類下面有很多鏈接。我現(xiàn)在想統(tǒng)計所有分類下面點擊次數(shù)最多的一個,并把其顏色做特殊處理!
大致的數(shù)據(jù)結(jié)構(gòu)如下:
{
"content": [
{
"id": "1",
"name": "htmldrive",
"url": "http://www.htmldrive.net/",
"cate": "前端開發(fā)",
"clickpoint": "100"
},
{
"id": "2",
"name": "17素材網(wǎng)",
"url": "http://www.17sucai.com/",
"cate": "前端開發(fā)",
"clickpoint": "151"
},
{
"id": "3",
"name": "阿里媽媽圖標(biāo)庫",
"url": "http://www.iconfont.cn/",
"cate": "前端開發(fā)",
"clickpoint": "2"
},
{
"id": "53",
"name": "Animate.css",
"url": "http://www.haorooms.com/uploads/example/Animatecss/",
"cate": "前端開發(fā)",
"clickpoint": "21"
},
{
"id": "55",
"name": "Dafont",
"url": "http://www.dafont.com/",
"cate": "字體",
"clickpoint": "1"
}
]
}
如何對這些數(shù)據(jù)進(jìn)行分類高亮顯示呢?
方法和思路
最好的處理方式是在后端PHP中對齊進(jìn)行處理。
思路:我們可以創(chuàng)建一個新的過渡數(shù)組,對原來的數(shù)組進(jìn)行循環(huán),創(chuàng)建一個分類的數(shù)組,然后把點擊次數(shù)中的最大值和ID放到這個數(shù)組中。通過比較,獲取分類中點擊次數(shù)最多的ID和點擊次數(shù),然后把這個次數(shù)最多的ID放在一個新的數(shù)組中,循環(huán)原來的數(shù)據(jù),通過inarray(),函數(shù)判斷次數(shù)最多的ID是不是在這個數(shù)組當(dāng)中,是的話,就給數(shù)據(jù)增加一個標(biāo)示字段1,不是的話就是0。那么標(biāo)示字段為1的就是分類中點擊次數(shù)最多的。
調(diào)整之后輸出的json是:
{
"content": [
{
"id": "1",
"name": "htmldrive",
"url": "http://www.htmldrive.net/",
"cate": "前端開發(fā)",
"clickpoint": "100",
"max": 0
},
{
"id": "2",
"name": "17素材網(wǎng)",
"url": "http://www.17sucai.com/",
"cate": "前端開發(fā)",
"clickpoint": "151",
"max": 1
},
{
"id": "3",
"name": "阿里媽媽圖標(biāo)庫",
"url": "http://www.iconfont.cn/",
"cate": "前端開發(fā)",
"clickpoint": "2",
"max": 0
},
{
"id": "53",
"name": "Animate.css",
"url": "http://www.haorooms.com/uploads/example/Animatecss/",
"cate": "前端開發(fā)",
"clickpoint": "21",
"max": 0
},
{
"id": "55",
"name": "Dafont",
"url": "http://www.dafont.com/",
"cate": "字體",
"clickpoint": "1",
"max": 0
}
]
}
php的代碼如下:
$sql = "select id,name,url,cate,clickpoint from commonwebsite order by id asc ";
$res= $db->getAll($sql);
$temp_arr = array();
foreach ($res as $key => $value) {
if(!isset($temp_arr[$value['cate']])){
$temp_arr[$value['cate']] = array();
$temp_arr[$value['cate']]['max'] = $value['clickpoint'];
$temp_arr[$value['cate']]['id'] = $value['id'];
}else{
if($value['clickpoint']>$temp_arr[$value['cate']]['max']){
$temp_arr[$value['cate']]['max'] = $value['clickpoint'];
$temp_arr[$value['cate']]['id'] = $value['id'];
}
}
}
$temp_id = array(); //創(chuàng)建一個存放ID的臨時數(shù)組
foreach ($temp_arr as $val) {//循環(huán)之前創(chuàng)建的臨時數(shù)組,存放分類和最多點擊次數(shù)的
$temp_id[] = $val['id']; //將點擊次數(shù)最多的ID賦值給了臨時數(shù)組
}
foreach ($res as $key => $vals) { //循環(huán)原來的數(shù)據(jù)
if(in_array($vals['id'], $temp_id)){//如果次數(shù)最多的ID在原來的數(shù)組的ID中,那個加一個字段max并設(shè)置其值為1
$res[$key]['max'] =1;
}else{
$res[$key]['max'] =0;//否則不是點擊次數(shù)最多的,設(shè)置為0
}
}
$result['content'] = $res;
die(json_encode($result)); //json輸出
exit();