Re: sorting troubles

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



At 02:49 AM 4/22/2006, William Stokes wrote:
I have a column in DB that contains this kind of data,
A20,B16,B17C14,C15,D13,D12 etc.

I would like to print this data to a page and sort it ascending by the
letter an descending by the number. Can this be done? Like

A20
B17
B16
C15
C14
D13
D12


Will, I can think of two ways to do this.

One way involves splitting each value into its two components so you can sort one ASC & the other DESC.

(First off, I'd seriously consider storing them in two separate DB fields. If you can do this, your problem is over because you can extract them in a query in just the order you want. If you're sorting them in opposite directions that's a pretty good clue that they're really separate data and should be stored separately.)

But you can split them on the fly in PHP. You can run preg_match() on each element of your array with a RegExp something like:

        /(\D)(\d+)/

(one non-numeric character followed by one or more numeric digits)

        preg_match("/(\D)(\d+)/", $aData($i), $aMatches)

is going to produce an array like:

        $aMatches = array(
                [0] = A20
                [1] = A
                [2] = 20
        )

Build a workspace array using those three match values, sort the way you want on [1] & [2], and extract your result array from [0].


An alternative way to do this, trickier but probably much faster, is to translate the initial letter into a value that's its inverse:

        $aFrom = array("A","B","C",..."Z");
        $aTo = array("Z","Y","X",..."A");

        $aTemp = str_replace($aFrom, $aTo, $aData);

This will translate the letters in all the elements of the data array into their inverse:

        B16 --> Y16
        A20 --> Z20
        B17 --> Y17
        ...

Then just do a reverse sort on $aTemp and you get:

        Z20
        Y17
        Y16

Then translate the letters back to their original values and you get:

        A20
        B17
        C16

Voila.

Paul
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux