note 92061 added to function.uksort

From: Date: Tue, 07 Jul 2009 14:58:16 +0000
Subject: note 92061 added to function.uksort
Groups: php.notes 
Request: Send a blank email to php-notes+get-158017@lists.php.net to get a copy of this message
If you need to periodically sort by grades (A, A+, D-, etc.), here is a compare function that compares strings by the case-insensitive method, unless it finds a grade, in which case it correctly sorts by putting "plus" grades first, unmarked grades second, and "minus" grades last. function cmp($a, $b) { $a = preg_replace('@^(a|an|the) @', '', $a); $b = preg_replace('@^(a|an|the) @', '', $b); //special code for grades if (strpos( $a, "+") !== false || strpos( $b, "+") !== false || strpos( $a, "-") !== false || strpos( $b, "-") !== false ){ $substrA = substr($a, 0, 1); $substrB = substr($b, 0, 1); $modifierA = (strlen($a) == 2) ? substr($a, 1, 1) : ""; $modifierB = (strlen($b) == 2) ? substr($b, 1, 1) : ""; if ($substrA == $substrB){ //figure out plusses and minuses. if ($modifierA == "+"){ return -1; } else if ($modifierB == "+"){ return 1; } if ($modifierA == "-"){ return 1; } else if ($modifierB == '-'){ return -1; } } else { return strcasecmp($a, $b); } } return strcasecmp($a, $b); } $grades = array( "C+" => 13 , "C" => 10 , "D+" => 8 , "B+" => 7 , "C-" => 6 , "A-" => 5 , "F" => 5 , "B" => 4 , "B-" => 4 , "D" => 3 , "D-" => 3 , "A+" => 1 ); uksort($grades, "cmp"); result: Array ( [A+] => 1 [A-] => 5 [B+] => 7 [B] => 4 [B-] => 4 [C+] => 13 [C] => 10 [C-] => 6 [D+] => 8 [D] => 3 [D-] => 3 [F] => 5 ) ---- Server IP: 69.147.83.197 Probable Submitter: 209.223.208.254 ---- Manual Page -- http://www.php.net/manual/en/function.uksort.php Edit -- https://master.php.net/note/edit/92061 Del: integrated -- https://master.php.net/note/delete/92061/integrated Del: useless -- https://master.php.net/note/delete/92061/useless Del: bad code -- https://master.php.net/note/delete/92061/bad+code Del: spam -- https://master.php.net/note/delete/92061/spam Del: non-english -- https://master.php.net/note/delete/92061/non-english Del: in docs -- https://master.php.net/note/delete/92061/in+docs Del: other reasons-- https://master.php.net/note/delete/92061 Reject -- https://master.php.net/note/reject/92061 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#158017) next »