SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    grasshoppa Snowbird122's Avatar
    Join Date
    Apr 2001
    Location
    Austin
    Posts
    353
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    php sort() oddity

    before the sort, my array looks like this:
    item [0]: cow
    item [1]: elepahnt
    item [2]: donkey
    item [3]: bear

    afterwards it looks like this:
    item [0]: bear
    item [1]: donkey
    item [2]: elephant
    item [3]: cow

    The first item is not being sorted. It is just being pushed to the end of the array. Any ideas?
    http://www.echo-consulting.net - Sound Solutions for Online Inspriations.

  2. #2
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If this odd sorting order is being caused because of upper/lower case problems it is because sort() does not sort alphabetically as you and I would - but by ASCII values.

    You can pass a flag in you call to sort to tell it to compare the items as strings. http://www.php.net/manual/en/function.sort.php

    You will se that on that page, a user has contributed some code for their own solution which uses usort() which itself will use a user defined function to compare the items to be sorted. If nothing else the code is interesting
    tim@sod.co.uk
    27-Mar-2001 01:40
    I was looking for a way to sort an array alphabetically. The first post points out that 'Ab' is different to 'AB' and you can't make it case insensitive (well, I couldn't). So I did it like this:
    PHP Code:
    function cmp ($a$b) { 
    $tmp[0]=strtoupper($a); 
    $tmp[1]=strtoupper($b); 
    sort($tmp); 
    return (
    strcmp(strtoupper($tmp[1]) , strtoupper($b))) ? : -1


    $listing[0]="AB"
    $listing[1]="yzZAZz"
    $listing[2]="YZzazZ"
    $listing[3]="LhaASD"
    $listing[4]="A"
    $listing[5]="aB"

    usort($listing"cmp"); 

    echo 
    implode(",",$listing); 
    Which produces:
    A,AB,aB,LhaASD,yzZAZz,YZzazZ

  3. #3
    grasshoppa Snowbird122's Avatar
    Join Date
    Apr 2001
    Location
    Austin
    Posts
    353
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your help. Actually, it is not a uppercase/lowercase problem because all my words are lower case. Maybe it has something to do with the way I am displaying the array.

    I am using
    while ($query_data = mysql_fetch_array($rstResult))
    to display the array. Any other ideas?
    http://www.echo-consulting.net - Sound Solutions for Online Inspriations.


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
  •