note 25959 rejected from function.uksort by victor
| From: | victor@php.net | Date: | Sun, 13 Oct 2002 12:16:33 +0000 |
| Subject: | note 25959 rejected from function.uksort by victor | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-38010@lists.php.net to get a copy of this message | ||
I couldn't find a function anywhere to sort a 2d array, so I ported something I wrote in
JavaScript. This sorts by a primary column, an optional secondary column, and in either ascending or
decending order. It is, however, a little slow. If you come up with a better one, please post here
and email it to me.
/* sort2D - sort a two-dimensional array by a given column and direction
arguments:
arIn - a two-dimentional array
intPrimary - the first column to sort by
intSecondary - the second column to sort by (use false or an empty string to sort only by primary)
boolDirection - the direction to sort (1/true = ascending, 0/false = decending)
returns:
a copy of arIn, sorted as specified */
function sort2D($aIn, $sPrimary, $sSecondary='', $bDirection=1) {
for($i=0; $i<count($aIn); $i++) {
for($j=0; $j<count($aIn); $j++) {
$bSwitchRows = false;
if(($bDirection) && (strcasecmp($aIn[$i][$sPrimary], $aIn[$j][$sPrimary]) < 0)) {
$bSwitchRows = true; }
if((!$bDirection) && (strcasecmp($aIn[$i][$sPrimary], $aIn[$j][$sPrimary]) > 0)) {
$bSwitchRows = true; }
if((strcasecmp($aIn[$i][$sPrimary], $aIn[$j][$sPrimary]) == 0) && ($sSecondary !==
"")) {
if(($bDirection) && (strcasecmp($aIn[$i][$sSecondary], $aIn[$j][$sSecondary]) < 0)) {
$bSwitchRows = true; }
if((!$bDirection) && (strcasecmp($aIn[$i][$sSecondary], $aIn[$j][$sSecondary]) > 0))
{ $bSwitchRows = true; }
}
if($bSwitchRows) {
$aTemp = $aIn[$j];
$aIn[$j] = $aIn[$i];
$aIn[$i] = $aTemp;
}
}
}
return($aIn);
}