Last active
August 29, 2015 14:17
-
-
Save egulhan/873191e072665814ef3f to your computer and use it in GitHub Desktop.
Sort ranged numbers using PHP
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 | |
| // Helper function | |
| /** | |
| * Sorts ranged numbers | |
| * @param $a | |
| * @param $b | |
| * @return int | |
| */ | |
| function sort_ranged_numbers($a, $b) | |
| { | |
| $a = trim($a); | |
| $b = trim($b); | |
| // pattern for ranged numbers like 3-5 | |
| $rangedNumPatt = '/^(\d+)\s*-\s*(\d+)/'; | |
| // example: 3, 4 | |
| if (is_numeric($a) && is_numeric($b)) { | |
| if ($a == $b) | |
| return 0; | |
| return ($a < $b) ? -1 : 1; | |
| } // example: 1-3, 3-5 | |
| else if (($r1 = preg_match($rangedNumPatt, $a, $m1)) && ($r2 = preg_match($rangedNumPatt, $b, $m2))) { | |
| // example: 1-3, 1-5 | |
| if ($r1 && $r2) { | |
| // if first digits same, sort by 2nd digits | |
| if ($m1[0] == $m2[0]) { | |
| if ($m1[1] == $m2[1]) | |
| return 0; | |
| return ($m1[1] < $m2[1]) ? -1 : 1; | |
| } // sort by 1st digits | |
| else { | |
| if ($m1[0] == $m2[0]) | |
| return 0; | |
| return ($m1[0] < $m2[0]) ? -1 : 1; | |
| } | |
| } | |
| } // example: 1-3, 5 | |
| else { | |
| // example: 1-3, 1 | |
| if (($r1 = preg_match($rangedNumPatt, $a, $m1)) && $m1[0] == $b) | |
| return -1; | |
| // example: 1, 1-3 | |
| else if (($r1 = preg_match($rangedNumPatt, $b, $m1)) && $m1[0] == $a) | |
| return 1; | |
| // example: 1-3, 5 | |
| else { | |
| if ($a == $b) | |
| return 0; | |
| return ($a < $b) ? -1 : 1; | |
| } | |
| } | |
| } | |
| ?> |
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 | |
| require('function.sort_ranged_numbers.php'); | |
| $numbers=array('1-2','3-4','1','1-3','3-8','2-4','2'); | |
| usort($numbers,'sort_ranged_numbers'); | |
| print_r($sizes); | |
| /* | |
| OUTPUT: | |
| Array | |
| ( | |
| [0] => 1 | |
| [1] => 1-2 | |
| [2] => 1-3 | |
| [3] => 2 | |
| [4] => 2-4 | |
| [5] => 3-4 | |
| [6] => 3-8 | |
| ) | |
| */ | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment