1

I would like to sort the following array on the second character [1] (1 to D):

$_SESSION['kartenstapel']=array(
                '11','12','13','14','15','16','17','18','19','1A','1B','1C','1D',
                '21','22','23','24','25','26','27','28','29','2A','2B','2C','2D',
                '31','32','33','34','35','36','37','38','39','3A','3B','3C','3D',
                '41','42','43','44','45','46','47','48','49','4A','4B','4C','4D',
                '51','52','53','54','55','56','57','58','59','5A','5B','5C','5D',
                'W1','W2','W3','W4','W5','W6','W7','W8','W9','WA','WB','WC','WD' 
  );

Ideal output would be the following:

$_SESSION['kartenstapel']=array(
                '11','21','31','41','51','W1','12','22','32','42','52','W2','13'...
2
  • 1
    Use usort() and apply your custom sorting function to it. Commented Aug 30, 2016 at 19:00
  • It works! Thank you for pointing that out! Commented Aug 30, 2016 at 19:08

3 Answers 3

1

You can use the usort function to pass your own custom comparing-function.

There are a couple of things to keep in mind here. The first thing you need to compare is the [1] character. However, naturally, D doesn't come after 1 (for example), so you'd need to do some manipulation. A neat trick is to treat this character as a hexdecimal number (e.g., by using base_convert and converting it to an integer. Second, if both string's second character is the same, you'd want to sort lexicographically, i.e., just return the result from strcmp. When you put it all together, you'll get something like this:

usort($_SESSION['kartenstapel'], function ($a, $b) {
    $cmp = base_convert($a[1], 16, 10) - base_convert($b[1], 16, 10);
    if ($cmp != 0) {
        return $cmp;
    }
    return strcmp($a, $b);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your good explanation! I will be using your function. :)
1

The following function worked for me. It was taken from and I only had to add "[1]": http://www.w3schools.com/php/showphp.asp?filename=demo_func_usort

Thanks to Rizier123.

function my_sort($a,$b){
    if ($a[1]==$b[1]) return 0;
    return ($a[1]<$b[1])?-1:1;
}

usort($_SESSION['kartenstapel'],"my_sort");

Comments

1

Since they're all only two characters, it looks like you could just sort by comparing the reverse of each string.

usort($_SESSION['kartenstapel'], function($a, $b) {
    return strcmp(strrev($a), strrev($b));
});

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.