note 66731 deleted from ref.array by felipe
| From: | felipe@php.net | Date: | Sun, 30 Dec 2007 19:24:45 +0000 |
| Subject: | note 66731 deleted from ref.array by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-134510@lists.php.net to get a copy of this message | ||
Note Submitter: php_spam at erif dot org
----
Public domain, yadda yadda. This is an extension of the assocSort below, patched up a bit.
Feedback would be wonderful.
<?php
function assocMultiSort(&$array,$keys,$directions=true) {
if (!is_array($array) || count($array) == 0) return true;
if (!is_array($keys)) { $keys = Array($keys); }
//we want "current" instead of necessarily the "zeroth" element; there may
not be a zeroth element
$test = current($array);
$assocSortCompare = '';
for ($i=0,$count=count($keys);$i<$count;$i++) {
$key = $keys[$i];
if (is_array($directions)) {
$direction = $directions[$i];
} else {
$direction = $directions;
}
if ($i > 0) $assocSortCompare .= 'if ($retval != 0) return $retval; ';
$assocSortCompare .= '$ax = $a["'.$key.'"]; $bx =
$b["'.$key.'"];';
//TODO -- if it's "blank", search up the list until we find something not blank
if (is_numeric($test[$key]) || ($test[$key] == ((int)$test[$key]))) {
if ($direction) {
$assocSortCompare.= ' $retval = ($ax == $bx) ? 0 : (($ax < $bx) ? -1 : 1);';
} else {
$assocSortCompare.= ' $retval = ($ax == $bx) ? 0 : (($ax < $bx) ? 1 : -1);';
}
} else {
if ($direction) {
$assocSortCompare.= ' $retval = strcmp($ax,$bx);';
} else {
$assocSortCompare.= ' $retval = strcmp($bx,$ax);';
}
}
}
$assocSortCompare.= ' return $retval;';
$assocSortCompare = create_function('$a,$b',$assocSortCompare);
$retval = usort($array,$assocSortCompare);
return $retval;
}
?>