note 102035 modified in function.usort by danbrown
| From: | danbrown@php.net | Date: | Mon, 24 Jan 2011 19:58:05 +0000 |
| Subject: | note 102035 modified in function.usort by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176253@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.example.org comes after b.example.com, etc.
<?php
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;
}
?>
--was--
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;
}
http://php.net/manual/en/function.usort.php