Re: sorting troubles

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

 



William Stokes wrote:
> Hello,
> 
> Any idea how to sort this?
> 
> 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? 

PHP has the usort() function which allows you to sort by another
function.  This allows you to very neatly sort by virtually any criteria.

I knocked up a fairly simple function to do the sort that you described.
The format for the comparison function is in the usort() documentation
as well as several examples.

<php
function weird_comparison($a, $b) {
    # return -1, 0, 1 if $a is less than, equal to or greater than $b
    if($a{0} > $b{0})
        return 1;
    elseif($a{0} < $b{0})
        return -1;
    else {
        $a_num = substr($a, 1);
        $b_num = substr($b, 1);
        if($a_num > $b_num)
            return -1;
        elseif($a_num < $b_num)
            return 1;
        else
            return 0;
    }
}

$arr = explode(',', 'A20,B16,B17,C14,C15,D13,D12');
print_r($arr);
usort($arr, 'weird_comparison');
print_r($arr);
?>


David

-- 
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