note 42535 added to function.usort
| From: | Raveler at telenet dot be | Date: | Thu, 20 May 2004 14:02:12 +0000 |
| Subject: | note 42535 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-69869@lists.php.net to get a copy of this message | ||
The array_alternate_multisort function written by robert below doesn't work. There are several
bugs in the code and it doesn't work when sorting by multiple keys because the order of the
first key isn't taken into account when sorting by the second key and so on. Also, because
robert uses strcasecmp the algorithm doesn't work properly with floats or other variable types.
Here's the improved version:
<?php
function SortArray() {
$arguments = func_get_args();
$array = $arguments[0];
$code = '';
for ($c = 1; $c < count($arguments); $c += 2) {
if (in_array($arguments[$c + 1], array("ASC", "DESC"))) {
$code .= 'if ($a["'.$arguments[$c].'"] !=
$b["'.$arguments[$c].'"]) {';
if ($arguments[$c + 1] == "ASC") {
$code .= 'return ($a["'.$arguments[$c].'"] <
$b["'.$arguments[$c].'"] ? -1 : 1); }';
}
else {
$code .= 'return ($a["'.$arguments[$c].'"] <
$b["'.$arguments[$c].'"] ? 1 : -1); }';
}
}
}
$code .= 'return 0;';
$compare = create_function('$a,$b', $code);
usort($array, $compare);
return $array;
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+42535
Delete -- http://master.php.net/manage/user-notes.php?action=delete+42535&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+42535&report=yes
Search -- http://master.php.net/manage/user-notes.php