背景和需求
就好比說頁面導航的左側是分類,分類下面有很多鏈接。我現在想統計所有分類下面點擊次數最多的一個,並把其顏色做特殊處理!
大致的數據結構如下:
{ "content": [ { "id": "1", "name": "htmldrive", "url": "http://www.htmldrive.net/", "cate": "前端開發", "clickpoint": "100" }, { "id": "2", "name": "17素材網", "url": "http://www.17sucai.com/", "cate": "前端開發", "clickpoint": "151" }, { "id": "3", "name": "阿裡媽媽圖標庫", "url": "http://www.iconfont.cn/", "cate": "前端開發", "clickpoint": "2" }, { "id": "53", "name": "Animate.css", "url": "http://www.haorooms.com/uploads/example/Animatecss/", "cate": "前端開發", "clickpoint": "21" }, { "id": "55", "name": "Dafont", "url": "http://www.dafont.com/", "cate": "字體", "clickpoint": "1" } ] }如何對這些數據進行分類高亮顯示呢?
方法和思路
最好的處理方式是在後端PHP中對齊進行處理。
思路:我們可以創建一個新的過渡數組,對原來的數組進行循環,創建一個分類的數組,然後把點擊次數中的最大值和ID放到這個數組中。通過比較,獲取分類中點擊次數最多的ID和點擊次數,然後把這個次數最多的ID放在一個新的數組中,循環原來的數據,通過inarray(),函數判斷次數最多的ID是不是在這個數組當中,是的話,就給數據增加一個標示字段1,不是的話就是0。那麼標示字段為1的就是分類中點擊次數最多的。
調整之後輸出的json是:
{ "content": [ { "id": "1", "name": "htmldrive", "url": "http://www.htmldrive.net/", "cate": "前端開發", "clickpoint": "100", "max": 0 }, { "id": "2", "name": "17素材網", "url": "http://www.17sucai.com/", "cate": "前端開發", "clickpoint": "151", "max": 1 }, { "id": "3", "name": "阿裡媽媽圖標庫", "url": "http://www.iconfont.cn/", "cate": "前端開發", "clickpoint": "2", "max": 0 }, { "id": "53", "name": "Animate.css", "url": "http://www.haorooms.com/uploads/example/Animatecss/", "cate": "前端開發", "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(); //創建一個存放ID的臨時數組 foreach ($temp_arr as $val) {//循環之前創建的臨時數組,存放分類和最多點擊次數的 $temp_id[] = $val['id']; //將點擊次數最多的ID賦值給了臨時數組 } foreach ($res as $key => $vals) { //循環原來的數據 if(in_array($vals['id'], $temp_id)){//如果次數最多的ID在原來的數組的ID中,那個加一個字段max並設置其值為1 $res[$key]['max'] =1; }else{ $res[$key]['max'] =0;//否則不是點擊次數最多的,設置為0 } } $result['content'] = $res; die(json_encode($result)); //json輸出 exit();