note 42535 deleted from function.usort by crell

From: Date: Thu, 31 Mar 2022 16:31:17 +0000
Subject: note 42535 deleted from function.usort by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-217831@lists.php.net to get a copy of this message
Note Submitter: Raveler at telenet dot be ---- 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; } ?>

« previous php.notes (#217831) next »