PHP比较两个版本的方法

PHP比较两个版本的方法 写app接口经常要用到  PHP接口的版本和app里面的版本做比较

 
 check($version)){
            list($major, $minor, $sub) = explode('.', $version);
            $integer_version = $major*10000 + $minor*100 + $sub;
            return intval($integer_version);
        }else{
            throw new ErrorException('version Validate Error');
        }
    }

    /**
     * 将数字转为版本
     * @param  Int     $version_code 版本的数字表示
     * @return String
     */
    public function integer_to_version($version_code){
        if(is_numeric($version_code) && $version_code>=10000){
            $version = array();
            $version[0] = (int)($version_code/10000);
            $version[1] = (int)($version_code%10000/100);
            $version[2] = $version_code%100;
            return implode('.', $version);
        }else{
            throw new ErrorException('version code Validate Error');
        }
    }

    /**
     * 检查版本格式是否正确
     * @param  String  $version 版本
     * @return Boolean
     */
    public function check($version){
        $ret = preg_match('/^[0-9]{1,3}\.[0-9]{1,2}\.[0-9]{1,2}$/', $version);
        return $ret? true : false;
    }

    /**
     * 比较两个版本的值
     * @param  String  $version1  版本1
     * @param  String  $version2  版本2
     * @return Int                -1:1<2, 0:相等, 1:1>2
     */
    public function compare($version1, $version2){
        if($this->check($version1) && $this->check($version2)){
            $version1_code = $this->version_to_integer($version1);
            $version2_code = $this->version_to_integer($version2);

            if($version1_code>$version2_code){
                return 1;
            }elseif($version1_code<$version2_code){
                return -1;
            }else{
                return 0;
            }
        }else{
            throw new ErrorException('version1 or version2 Validate Error');
        }
    }

} // class end

$version = '2.7.1';

$obj = new Version();

// 比较两个版本
$version1 = '2.9.9';
$version2 = '10.0.1';

$result = $obj->compare($version1, $version2);
echo $result; // -1

// 比较两个版本
$version1 = '2.9.9';
$version2 = '1';

$result = $obj->compare($version1, $version2);
echo $result; // 1
?>

查看原文:http://newmiracle.cn/?p=1828
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值