1. 程式人生 > >TEC-006-數據模糊處理

TEC-006-數據模糊處理

PHP

數據在用戶層要做模糊化處理,數據範圍連續,沒有重合,想了一個解決方案,通過對範圍的起始位置排序用二分查找獲取模糊值區間;

數據轉換格式如下:
eg.1
50平以下(<50)
50-70平(>=50,<70)
70-90平(>=70,<90)
90-110平(>=90,<110)
110-130平(>=110,<130)
130-150平(>=130,<150)
150-200平(>=150,<200)
200平以上(>=200)
eg.2
一個月以內(0-30天)
兩個月以內(31-60天)
三個月以內(61-90天)
半年以內(91-180天)
一年以內(181天-365天)
一年以上(365天以上)
demo:
class VlCode {

const CONSTRUCTION_AREA=[50,70,90,110,130,150,200];
const FINAL_PRICE=[100,150,200,250,300,400,500,800,1000];
const LOAN_AMOUNT=[30,50,100,150,200,250,300,400,500];
const LOAN_DATE=[30,31,60,61,90,91,180,181,365];
const LOAN_DATE_CEIL=[
‘-1‘=>"一個月以內",
‘1‘=>"兩個月以內",
‘3‘=>"三個月以內",
‘5‘=>"半年以內",
‘7‘=>"一年以內",
‘9‘=>"一年以上"
];
/**

  • 描述: 獲取範圍值轉義
  • @date:2018年4月9日 上午10:00:44
  • @$arr 範圍值,@$target 參考值
  • @author lwy
    */
    static public function getRanges($arr,$target,$ceil=‘‘){
    if(empty($target)||$target<0){
    return ‘無‘;
    }
    $index=self::binarySearchAsc($arr,$target);
    if($ceil==‘date‘){
    $changeArr=self::LOAN_DATE_CEIL;
    return @$changeArr[$index];
    }
    $count=count($arr);
    $last=$ceil;
    if($index==-1){
    $last=‘以下‘;
    $ret=$arr[0];
    }elseif($index==$count){
    $last=‘以上‘;
    $ret=$arr[$index-1];
    }else{
    $ret=$arr[$index].‘-‘.$arr[$index+1];
    }
    if(empty($ceil)){
    return $ret;
    }else{
    return $ret.$last;
    }
    }
    /**
  • 描述: 獲取時間差(天)
  • @date:2018年4月9日 上午11:01:45
  • @author lwy
    /
    static public function getDays($begin,$end=‘‘){
    $end=empty($end)?date(‘Y-m-d‘):$end;
    $begin=empty($begin)?date(‘Y-m-d‘):date(‘Y-m-d‘,strtotime($begin));
    $t = strtotime($end) - strtotime($begin);//拿當前時間-開始時間 = 相差時間
    return $days = $t/(3600
    24);//此時間單位為 天
    }
    /**
  • 描述: 二分查找 升序查找區間範圍的數據
  • @date:2018年4月9日 上午10:57:51
  • @author lwy
    */
    //二分查找
    static public function binarySearchAsc(Array $arr, $target) {
    $last=count($arr);
    $low = 0;
    $high = $last - 1;
    while($low <= $high) {
    $mid = floor(($low + $high) / 2);
    $next=$mid+1;
    $pre=$mid-1;
    //#找到元素
    if($arr[$mid]==$target){
    return $mid;}elseif($arr[$mid]>$target&&$pre>=0&&$target>=@$arr[$pre]){
    br/>}elseif($arr[$mid]>$target&&$pre>=0&&$target>=@$arr[$pre]){
    }elseif($target>=$arr[$high]){
    return $last;
    }elseif($pre<0){
    return $pre;
    }
    //if($arr[$mid] == $target) return $mid;
    //#中元素比目標大,查找左部
    if($arr[$mid] > $target) $high = $mid - 1;
    //#重元素比目標小,查找右部
    if($arr[$mid] < $target) $low = $mid + 1;
    }
    //#查找失敗
    return false;
    }
    }

$arr = array(1, 3, 5, 7, 9, 11,13);
echo VlCode::getRanges($arr,8,‘平‘);
$date=‘2017-05-12‘;
$days=VlCode::getDays($date);
echo VlCode::getRanges(VlCode::LOAN_DATE,$days,‘date‘);

TEC-006-數據模糊處理