SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to sort an array alphabetically

    Hi, I need a simple solution to sort an array alphabetically, here is my code:


    PHP Code:
        <?php while(sort($cities=dbFetchArray($results)))
                       {
    ?>
                         <option value="<?=$cities['grd']?>"> <?=$cities['grd']?></option>
                          <?php }?>
    As you can see I added the sort function, but doesnt work.. any ideas?

  2. #2
    Avid Logophile silver trophy
    ParkinT's Avatar
    Join Date
    May 2006
    Location
    Central Florida
    Posts
    2,329
    Mentioned
    191 Post(s)
    Tagged
    4 Thread(s)
    I found this, at the top of the list, of a quick Google search: http://www.w3schools.com/php/func_array_sort.asp
    Even the example sorts a set of strings alphabetically.
    Don't be yourself. Be someone a little nicer. -Mignon McLaughlin, journalist and author (1913-1983)


    Git is for EVERYONE
    Literally, the best app for readers.
    Make Your P@ssw0rd Secure
    Leveraging SubDomains

  3. #3
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hi thanks for that.. as you can see I added the sort function .. but it doesn't seem to sort alphabetically.. what I am doing wrong?

  4. #4
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    69 Post(s)
    Tagged
    0 Thread(s)
    You're trying to do too much in one line. Make your while pull the array, then sort it inside the loop.

  5. #5
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,023
    Mentioned
    62 Post(s)
    Tagged
    0 Thread(s)
    Since you are pulling from the database make the database do the sorting with an ORDER BY clause.

    Code sql:
    SELECT grd FROM cities ORDER BY grd DESC

    Under normal circumstances SQL can sort considerably faster than PHP, so it is more efficient to use SQL ordering at query time.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •