Re: A better way to sort?
| From: | Bobby Patel | Date: | Wed, 23 Apr 2003 20:15:24 +0000 |
| Subject: | Re: A better way to sort? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-145073@lists.php.net to get a copy of this message | ||
Do you use this information from the file one time or alot of times? If you
use it alot, then you can just create a database table with columns
(firstName, lastName, Number, city). And then just run queries using the
"Order By" clause.
"Steve Keller" <skeller@healthtvchannel.org> wrote in message
news:5.1.1.6.0.20030423104740.00ae1c58@207.159.149.141...
> 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
>