PHP如何在特定要求下增加版本号

Qui*_*eys 2 php increment

我想$numero1 = "1.0.1"通过以下规则集增加版本号。

  1. 增加最后一个数字(第二个周期之后的数字)。
  2. 如果增加的数字大于 9,则设置为 0 并增加第二个数字。
  3. 如果第二个数字也大于 9(递增后),则设置为 0 并递增第一个数字。

所以我所做的是$numerosumado = $numero1 + 1但由于点而不起作用。所以我的问题是我该怎么做?

Azi*_*leh 6

我认为这个工作更顺畅,没有太多的 if/loops:

$a = '1.9.9';
$a = str_replace('.', '', $a) + 1;
$a = implode('.', str_split($a));
echo $a;
Run Code Online (Sandbox Code Playgroud)

基本上将其转换为数字,递增然后将其转换回来。

唯一的缺点是第一个整数必须是>= 1。所以0.0.1不会工作。我假设它总是>= 1.0.0来自您发布的内容。


Axe*_*xel 5

注意:这只是众多方法中的一种...

有关进一步的解释,请参阅此工作片段中的注释。

<?php
$numero1 = "1.9.9";
$numerosumado = explode( ".", $numero1 ); // array( "1", "9", "9" )
if ( ++$numerosumado[2] > 9 ) { // if last incremented number is greater than 9 reset to 0
    $numerosumado[2] = 0;
    if ( ++$numerosumado[1] > 9 ) { // if second incremented number is greater than 9 reset to 0
        $numerosumado[1] = 0;
        ++$numerosumado[0]; // incremented first number
    }
}
$numerosumado = implode( ".", $numerosumado ); // implode array back to string
Run Code Online (Sandbox Code Playgroud)

提示:递增数字字符串(例如“1”或“0.9”)将自动将类型更改为整数或浮点数并按预期递增。


编辑:这个解决方案更优雅一些。

<?php
$version = "9.9.9";
for ( $new_version = explode( ".", $version ), $i = count( $new_version ) - 1; $i > -1; --$i ) {
    if ( ++$new_version[ $i ] < 10 || !$i ) break; // break execution of the whole for-loop if the incremented number is below 10 or !$i (which means $i == 0, which means we are on the number before the first period)
    $new_version[ $i ] = 0; // otherwise set to 0 and start validation again with next number on the next "for-loop-run"
}
$new_version = implode( ".", $new_version );
Run Code Online (Sandbox Code Playgroud)