note 102035 added to function.usort

From: Date: Mon, 24 Jan 2011 19:55:40 +0000
Subject: note 102035 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-176252@lists.php.net to get a copy of this message
I had to sort a result set by host. I made this comparator function to use in usort calls. Sorts by host segment so that a.org comes after b.com, etc. function hostcmp($a, $b) { $a = strtolower($a); $b = strtolower($b); if ($a == $b) { return 0; } $parts_a = array_reverse(explode('.', $a)); $parts_b = array_reverse(explode('.', $b)); $max = max(count($parts_a), count($parts_b)); for ($i=0; $i < $max; $i++) { if (($i < count($parts_a)) && ($i < count($parts_b))) { if ($c = strcmp($parts_a[$i],$parts_b[$i])) { return $c; } } else { // Return numeric cmp on array sizes. PHP doesn't have a <=> operator, so emulate it. //return count($parts_a) <=> count($parts_b); return count($parts_a) == count($parts_b) ? 0 : (count($parts_a) < count($parts_b) ? -1 : 1); } } return 0; } ---- Server IP: 213.249.64.162 Probable Submitter: 80.101.188.146 ---- Manual Page -- http://www.php.net/manual/en/function.usort.php Edit -- https://master.php.net/note/edit/102035 Del: integrated -- https://master.php.net/note/delete/102035/integrated Del: useless -- https://master.php.net/note/delete/102035/useless Del: bad code -- https://master.php.net/note/delete/102035/bad+code Del: spam -- https://master.php.net/note/delete/102035/spam Del: non-english -- https://master.php.net/note/delete/102035/non-english Del: in docs -- https://master.php.net/note/delete/102035/in+docs Del: other reasons-- https://master.php.net/note/delete/102035 Reject -- https://master.php.net/note/reject/102035 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#176252) next »