LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   php sort help - sort numerical descending then by alphabetical? (https://www.linuxquestions.org/questions/programming-9/php-sort-help-sort-numerical-descending-then-by-alphabetical-710551/)

RavenLX 03-10-2009 01:52 PM

php sort help - sort numerical descending then by alphabetical?
 
Using PHP 5.x.

I would like to sort a set of values first numerically, then alphabetically. For example, here's my code so far:

Code:

<?php

        print "<p style=\"font-family:verdana;font-size:10pt\">\n";
        $myArray = array("1223:starfruit", "34112:oranges", "1223:zucchini", "321:apples", "34112:pears", "1223:tomatoes");

        rsort($myArray, SORT_NUMERIC);

        for($i = 0; $i <= count($myArray); $i++) {
                print "$myArray[$i]<br />\n";
        }
        print "</p>\n";
?>

The output is this:

Code:

34112:pears
34112:oranges
1223:tomatoes
1223:zucchini
1223:starfruit
321:apples

I would like the output to be this instead:

Code:

34112:oranges
34112:pears
1223:starfruit
1223:tomatoes
1223:zucchini
321:apples

I have fiddled with array_multisort but I can't seem to get my head around it or the many sort routines in PHP. Help would be appreciated.

graemef 03-10-2009 10:41 PM

You want to look at usort, where it sorts using a user defined function, you will then need to write your own function that will compare the values, first comparing the number and if they are equal then compare the characters.

Telemachos 03-11-2009 06:42 AM

I knew this thread sounded familiar...

RavenLX 03-11-2009 08:35 AM

Thank you both. Yes, that was my thread. The thing is, the perl functions I ended up writing to do it (there were TWO of them that had to work together) might not work in PHP. I have to start from scratch again, it looks like. That takes time and I'm to finish this whole project this week. If I have to rewrite the functions I won't be able to finish in time. :(

So what I'll do is not have it sort the items alphabetically after values are sorted and get the rest of the project finished, and then just go back and try to work more on the alphabetical thing later. Perl and PHP are very similar (I was easily able to port another function into PHP from perl that I needed) but not everything is similar. Some things I have to do over.

I was hoping that PHP already *had* a function that would take care of it without me resorting to having to re-invent the wheel all over again.


All times are GMT -5. The time now is 10:52 AM.