首页 > Web开发 > 详细

PHP比较两个版本的方法

时间:2019-11-15 10:32:24      阅读:87      评论:0      收藏:0      [点我收藏+]

PHP比较两个版本的方法 写app接口经常要用到 PHP接口的版本和app里面的版本做比较 如果app版本低于接口版本 那么就要提示他升级
<pre>
<?php
/**
* 版本处理类,提供版本与数字互相转换,方便入库后进行比较筛选
* Date: 2015-06-30
* Author: fdipzone
* ver: 1.0
*
* Func:
* public version_to_integer 将版本转为数字
* public integer_to_version 将数字转为版本
* public check 检查版本格式是否正确
* public compare 比较两个版本的值
*/

class Version{ // class start

/**
* 将版本转为数字
* @param String $version 版本
* @return Int
*/
public function version_to_integer($version){
if($this->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
?>
</pre>

PHP比较两个版本的方法

原文:https://www.cnblogs.com/newmiracle/p/11864785.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!