Array sort function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
user___
Forum Contributor
Posts: 297
Joined: Tue Dec 05, 2006 3:05 pm

Array sort function

Post by user___ »

Hi guys,
I need a function to sort an array whose keys are strings and by defining their size I need the array sorted from the longest to the shortest key. I have searched on the net and I tried to create it on my own but I did not have a sorted array as a result.

BTW:Both keys and values are strings.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

What have you coded so far? Post what you have done.
miro_igov
Forum Contributor
Posts: 485
Joined: Fri Mar 31, 2006 5:06 am
Location: Bulgaria

Post by miro_igov »

Code: Select all

ksort()
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Based on what you are saying, you may need to create a couple of arrays (one of keys and one of values), sort the key array to be what you want, then put the original in that order. This may not be the best way to it.
josa
Forum Commoner
Posts: 75
Joined: Mon Jun 24, 2002 4:58 am
Location: Sweden

Post by josa »

Do you mean something like this?

Code: Select all

function cmp($a, $b)
{
    $len_a = strlen($a);
    $len_b = strlen($b);
    if ($len_a > $len_b)
        return -1;
    else if ($len_a < $len_b)
        return 1;
    else
        return 0;
}

uksort($arr, cmp);
/josa
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Have you tried it? Does it work?
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post by bokehman »

Everah wrote:Based on what you are saying, you may need to create a couple of arrays (one of keys and one of values), sort the key array to be what you want, then put the original in that order. This may not be the best way to it.
There's no need for any of that. Just use array_multisort() creatively. What about this:

Code: Select all

array_multisort(array_map('strlen', array_keys($your_array)), SORT_DESC, $your_array);
user___
Forum Contributor
Posts: 297
Joined: Tue Dec 05, 2006 3:05 pm

Reply

Post by user___ »

Guys, thank you for all replies. So, I created my application to use more than one arrays but imagine what happens when I sort them by key:

Code: Select all

$array = array("key"=>"value",
                        "tmp"=>"This key's length is the same as the first one"
                       );
so this way does not work, but the sample code that bokehman posted does work.

Thank you man.
Post Reply