Page 1 of 1

Array sort function

Posted: Tue Sep 04, 2007 10:10 am
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.

Posted: Tue Sep 04, 2007 10:46 am
by RobertGonzalez
What have you coded so far? Post what you have done.

Posted: Tue Sep 04, 2007 11:31 am
by miro_igov

Code: Select all

ksort()

Posted: Tue Sep 04, 2007 11:36 am
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.

Posted: Tue Sep 04, 2007 12:33 pm
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

Posted: Tue Sep 04, 2007 12:39 pm
by RobertGonzalez
Have you tried it? Does it work?

Posted: Tue Sep 04, 2007 12:43 pm
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);

Reply

Posted: Tue Sep 04, 2007 1:21 pm
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.