1

Im stuck on a sorting problem, I have an array with 10 numbers (1-10) and I need to sort the in the following way where 10 would come after 1, for example...

desired outcome

$arr['a1','a10','a2','a3','a4','a5','a6','a7','a8','a9'];

actual outcome

$arr['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10'];

sort($arr);

$arr['a10','a1','a2','a3','a4','a5','a6','a7','a8','a9'];

I don't know the name of this type of sorting or how to perform it, if anyone could help me it would much appreciated.

NOTE: the numbers are part of a string

6
  • What would be the desired outcome if you add 20 and 100 to the incoming array? Commented Aug 3, 2012 at 17:45
  • What's the application of such a sort order? Commented Aug 3, 2012 at 17:45
  • @Travis I have not gotten that far as i have an array smaller than 100 but it would probably be something like 1,10,100,2,200 Commented Aug 3, 2012 at 17:46
  • Can we "safely" assume that all the string values are actually numbers? Commented Aug 3, 2012 at 17:48
  • sorry I should have mentioned that they are strings Commented Aug 3, 2012 at 17:50

3 Answers 3

6

Try sort($arr,SORT_STRING) to explicitly treat the input as strings.

EDIT: Now that you've given your actual strings, try this:

usort($arr,function($a,$b) {
    $a = explode("=",$a);
    $b = explode("=",$b);
    return $a[0] == $b[0] ? strcmp($a[1],$b[1]) : strcmp($a[0],$b[0]);
});
Sign up to request clarification or add additional context in comments.

4 Comments

OK I've been testing it and it doest not work with the string that I have which is $arr = array('ASINList.ASIN.2=1580800939','ASINList.ASIN.1=1846031249 ','ASINList.ASIN.10=0340912081 ','ASINList.ASIN.3=1580800939');
ok thanks I sorted it out, I managed to sort by keys, thanks.
Ah, well, that's because = > 0, so 1= > 10. No wonder. Will edit with answer.
actually I would love to hear your answer
0

Sure, you want to sort alphabetically, not numerically.

sort($arr, SORT_STRING);

ref: http://php.net/manual/en/function.sort.php

1 Comment

yeah i write answers slowly so kolink probably answered as I was writing
0

You can change the behaviour of sort with it's second parameter.

Try this:

sort($arr, SORT_STRING);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.