简体   繁体   English

某些字符上的PHP排序数组 - > sort($ array [2])

[英]PHP sort array on certain character --> sort($array[2])

I would like to sort the following array on the second character [1] (1 to D): 我想在第二个字符[1](1到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'...

You can use the usort function to pass your own custom comparing-function. 您可以使用usort函数传递自己的自定义比较函数。

There are a couple of things to keep in mind here. 这里有几点要记住。 The first thing you need to compare is the [1] character. 你需要比较的第一件事是[1]字符。 However, naturally, D doesn't come after 1 (for example), so you'd need to do some manipulation. 然而,自然地, D不会在1之后(例如),所以你需要做一些操作。 A neat trick is to treat this character as a hexdecimal number (eg, 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, ie, just return the result from strcmp . When you put it all together, you'll get something like this: 一个巧妙的技巧是将此字符视为十六进制数字(例如,通过使用base_convert并将其转换为整数。其次,如果两个字符串的第二个字符相同,则您需要按字典顺序排序,即只返回结果来自strcmp 。当你把它们放在一起时,你会得到这样的东西:

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);
});

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 它取自我,我只需要添加“[1]”: http//www.w3schools.com/php/showphp.asp?filenamename = demo_func_usort

Thanks to Rizier123. 感谢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");

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));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM