Last active
January 19, 2018 08:58
-
-
Save kphrx/046a6950269877d12bd2d2cbb8ef8de9 to your computer and use it in GitHub Desktop.
version list sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require('VersionSort.php'); | |
$versionArray = ['2.0.0', '1.1.0', '1.0.0', '1.1.0-dev', '2.0.0-dev']; | |
VersionSort::ascendingSort($versionArray); | |
print_r($versionArray); | |
/* | |
Array | |
( | |
[0] => 1.0.0 | |
[1] => 1.1.0-dev | |
[2] => 1.1.0 | |
[3] => 2.0.0-dev | |
[4] => 2.0.0 | |
) | |
*/ | |
VersionSort::descendingSort($versionArray); | |
print_r($versionArray); | |
/* | |
Array | |
( | |
[0] => 2.0.0 | |
[1] => 2.0.0-dev | |
[2] => 1.1.0 | |
[3] => 1.1.0-dev | |
[4] => 1.0.0 | |
) | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class VersionSort { | |
public static function ascendingSort(array &$versionArray) { | |
return usort($versionArray, 'self::ascendingCompare'); | |
} | |
public static function descendingSort(array &$versionArray) { | |
return usort($versionArray, 'self::descendingCompare'); | |
} | |
private static function ascendingCompare($a, $b) { | |
if (version_compare($a, $b, '==')) | |
return 0; | |
return version_compare($a, $b, '<') ? -1 : 1; | |
} | |
private static function descendingCompare($a, $b) { | |
if (version_compare($a, $b, '==')) | |
return 0; | |
return version_compare($a, $b, '>') ? -1 : 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment