A better way to sort?
| From: | Steve Keller | Date: | Wed, 23 Apr 2003 19:24:55 +0000 |
| Subject: | A better way to sort? | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-145071@lists.php.net to get a copy of this message | ||
Hey all,
I've just written a function to do what I want, but I thought I'd offer up my problem and see who has a better idea, because the way I did it seems clunky to me at best.
We have a data file with delimited fields that we're reading into an array in PHP, so we have something like this as our array:
"bob--jones--3335555--pittsburgh"
"mark--humphries--2521119--san bernadino"
and so on. Four columns, delimited with "--". I need to be able to display that data on a page sorted based on any of those columns. What I ended up writing is a function that first explodes the element into a new array, then swaps element[0] with element[sort-column], then implodes it again and puts it back in the original array. Once Ive done that for every element of the original array, I then do a natcasesort on that array, then do the bit where I swap element[0] and element[sort-column] to set everything right and then return the array.
Like I said, it seems like a cludge at best, and I'm open to better suggestions.
Here's the function I'm using ($arr being the array, $col the integer of the column to sort by, $delimiter the seperator, and $reverse as 0 or 1)
function columnsort ($arr, $col, $delimiter, $reverse) {
foreach ($arr as $key => $thisItem) {
$thisItemArray = explode($delimiter, $thisItem);
$tempValue = $thisItemArray[$col];
$thisItemArray[$col] = $thisItemArray[0];
$thisItemArray[0] = $tempValue;
$thisItem = implode($delimiter, $thisItemArray);
$arr[$key] = $thisItem;
}
if ($reverse) { rsort($arr); }
else { natcasesort($arr); }
foreach ($arr as $key => $thisItem) {
$thisItemArray = explode($delimiter, $thisItem);
$tempValue = $thisItemArray[$col];
$thisItemArray[$col] = $thisItemArray[0];
$thisItemArray[0] = $tempValue;
$thisItem = implode($delimiter, $thisItemArray);
$arr[$key] = $thisItem;
}
return $arr;
}
--
S. Keller
UI Engineer
The Health TV Channel, Inc.
(a non - profit organization)
3820 Lake Otis Pkwy.
Anchorage, AK 99508
907.770.6200 ext.220
907.336.6205 (fax)
Email: skeller@healthtvchannel.org
Web: www.healthtvchannel.org