note 25959 added to function.uksort
| From: | josh at endquote dot spamissilly dot com | Date: | Sat, 12 Oct 2002 21:10:08 +0000 |
| Subject: | note 25959 added to function.uksort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-37987@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);
}
--
http://www.php.net/manual/en/function.uksort.php
http://master.php.net/manage/user-notes.php?action=edit+25959
http://master.php.net/manage/user-notes.php?action=delete+25959
http://master.php.net/manage/user-notes.php?action=reject+25959