开发者

Convert and reconvert a version to number to store in database

开发者 https://www.devze.com 2023-02-21 12:28 出处:网络
is there any algorithm to convert an string like 1.0.0 to a sortable number via PHP? It should be able to convert to same string again. It\'s not possible to just remove dots. Also length of version

is there any algorithm to convert an string like 1.0.0 to a sortable number via PHP?

It should be able to convert to same string again. It's not possible to just remove dots. Also length of version is unknown, for example 1.0.0, 11.2开发者_StackOverflow22.0, 0.8.1526


If you just want to sort versions, there is no need to convert.

<?php 
$versions = array('1.0.0', '11.222.0', '0.8.1256');
usort($versions, 'version_compare');

var_dump($versions);
array(3) {
  [0]=>
  string(8) "0.8.1256"
  [1]=>
  string(5) "1.0.0"
  [2]=>
  string(8) "11.222.0"
}


If you want to compare versions numbers, you could just use the version_compare() function.


And if you have an array of versions that you need to sort, you could use a function such as usort() / uasort(), with a callback based on version_compare().


If you insist on an arbitrary length there is no way to uniquely map the numbers with at the same time maintaining the ordering criterion. Maybe you just want to sort the version numbers without conversion (see other answers)?


If you expect version segmentation with numbers like 12345 (eg. 0.9.12345.2), then you may be best off exploding the string and storing each segment in separate field in SQL.

That way you can sort it how ever you wish.


One option would be using explode:

function cmp($a, $b)
{
    $a = explode('.', $a);
    $b = explode('.', $b);

    $m = min(count($a), count($b));

    for ($i = 0; $i < $m; $i++) {
      if (intval($a[$i]) < intval($b[$i]))
        return -1;
      else
        return 1;
    }

    return 0;
}

EDIT: Didn't know about version_compare, that might be a better option if it works as you need.


Here are a couple of functions that convert version to string and vice-versa.

So you can store the strings in your database and be able to sort them. I've used a length of 5 char but you can adapt to your needs.

function version_to_str($version) {
    $list = explode('.', $version);
    $str = '';
    foreach ($list as $element) {
        $str .= sprintf('%05d', $element);
    }
    return $str;
}
function str_to_version($str) {
    $version = array();
    for ($i=0; $i<strlen($str); $i+=5) {
        $version[] = intval(substr($str, $i, 5));
    }
    return implode('.', $version);
}

$versions = array('1.0.0', '11.222.0', '0.8.1526');

$versions = array_map("version_to_str", $versions);
sort($versions);
$versions = array_map("str_to_version", $versions);
print_r($versions);

output:

Array
(
    [0] => 0.8.1526
    [1] => 1.0.0
    [2] => 11.222.0
)
0

精彩评论

暂无评论...
验证码 换一张
取 消