Last active
September 21, 2022 07:51
-
-
Save coclav/2a9ff41b81ec1e9b3365c3c82c82a7be to your computer and use it in GitHub Desktop.
PHP Laravel sort by semver, software version or version-dotted number
This file contains hidden or 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 | |
use Illuminate\Support\Collection; | |
function sortSemVer(Collection $data) | |
{ | |
$mapped = $data->map(function ($a, $i) { | |
return [ | |
'index' => $i, | |
'value' => str_split($a), | |
]; | |
}); | |
$mapped = $mapped->sortBy([function ($a, $b) { | |
$i = 0; | |
$l = min(count($a['value']), count($b['value'])); | |
// find the "first" value to compare in the string | |
while ($i < $l && $a['value'][$i] === $b['value'][$i]) { | |
$i++; | |
} | |
if ($i === $l) { | |
return count($a['value']) - count($b['value']); | |
} | |
if (is_numeric($a['value'][$i]) && is_numeric($b['value'][$i])) { | |
return $a['value'][$i] - $b['value'][$i]; | |
} | |
return $a['value'][$i] - $b['value'][$i]; | |
}]); | |
//$mapped.sort(sort[order] || sort.asc); | |
return $mapped->map(function ($el) use ($data) { | |
return $data[$el['index']]; | |
}); | |
} | |
$array = collect(['5.05.1', '5', '4.21.0.0.0.24', '4.21.0.0.2', '4.21.0.0.1', '4.22.0', '6.1.0', '5.1.0', '2', '4.1']); | |
dump(sortSemVer($array)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment