วันศุกร์ที่ 27 ธันวาคม พ.ศ. 2556

start end format display number


abstract class StartEnd{
    protected $m = array();
    public function push($data){
        if (count($this->m)==0){
           $this->m[1] = $this->m[0] = $data;
        }else{
           $this->m[1] = $data;
        }
    }
    public function __toString(){
        if (count($this->m)==0){
            return '';
        }elseif ($this->m[0] == $this->m[1]){
            return (string)$this->m[0];
        }else{
            return $this->m[0].'-'.$this->m[1];
        }
    }
    public static function getFormat(array $a){
        $groups = array();
        $prev = -1;
        static::sort($a);
        foreach($a as $i){
              if ($prev !== static::getPrev($i)){
                     $se = new static();
                     $groups[] = $se;
              }
              $se->push($prev = $i);
        }
        return implode(',',$groups);
    }
    abstract public static function sort(&$a);
    abstract public static function getPrev($i);
}
class StartEndNumber extends StartEnd{
    public static function sort(&$a){
        sort($a,SORT_NUMERIC);
    }
    public static function getPrev($i){
        return $i-1;
    }
}
class StartEndDay extends StartEnd{
    protected static $enum = array('MON','TUE','WED','THU','FRI','SAT','SUN');
    public static function daySort($val1,$val2){
        return array_search($val1,static::$enum)-array_search($val2,static::$enum);
    }
    public static function sort(&$a){
        usort($a,'StartEndDay::daySort');
    }
    public static function getPrev($i){
        $position = array_search($i,self::$enum);
        if ($position === false){
                return false;
        }else{
                return self::$enum[$position-1];
        }
    }
}


$a = array(1,4,3,2,5,9,10,12);
echo StartEndNumber::getFormat($a),' '; //1-5,9-10,12

$a = array('TUE','MON','WED','FRI','SAT');
echo StartEndDay::getFormat($a); //MON-WED,FRI-SAT

ไม่มีความคิดเห็น:

แสดงความคิดเห็น