Array sort function
Moderator: General Moderators
Array sort function
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.
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.
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Code: Select all
ksort()- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Do you mean something like this?
/josa
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);- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
There's no need for any of that. Just use array_multisort() creatively. What about this: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.
Code: Select all
array_multisort(array_map('strlen', array_keys($your_array)), SORT_DESC, $your_array);Reply
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:
so this way does not work, but the sample code that bokehman posted does work.
Thank you man.
Code: Select all
$array = array("key"=>"value",
"tmp"=>"This key's length is the same as the first one"
);Thank you man.