How to sort versioning info

巧了我就是萌 提交于 2020-01-21 01:03:08

问题


What's the right way, to handle versioning indicators like 2.4 or 2.4.0.9 etc. to get the ability of sorting versions.

PHP says, that 1.3.4 is not a valid integer, but also a non-valid number.

array('2.4','2.3.4','2.4.0.9')

回答1:


PHP has a version_compare function. Use usort to sort it. Like following. :)

$a = array('2.4','2.3.4','2.4.0.9');
usort($a, 'version_compare');



回答2:


Or, just use natsort:

$array = array('2.4','2.16.6','2.3.4','2.4.0.9');
natsort($array);
print_r($array);

#Array ( [2] => 2.3.4 [0] => 2.4 [3] => 2.4.0.9 [1] => 2.16.6 )



回答3:


Storing it as a string allows you to make use of the version_compare() function:

$versions = array('2.4','2.3.4','2.4.0.9');
usort($versions, 'version_compare');


来源:https://stackoverflow.com/questions/8690823/how-to-sort-versioning-info

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!