按其值的最后几个字符对数组进行排序?

时间:2022-12-27 16:01:27

In PHP, how might one sort an array by the last couple of characters of its values? Take, for example, the following array:

在PHP中,如何通过其值的最后几个字符对数组进行排序?以,例如,以下数组:

$donuts[0] = "Chocolate 02";
$donuts[1] = "Jelly 16";
$donuts[2] = "Glazed 01";
$donuts[3] = "Frosted 12";

After the sort, the array would look like this (note the order based on the last two characters of each value... also note the rewritten indexes):

排序后,数组看起来像这样(注意基于每个值的最后两个字符的顺序......还要注意重写的索引):

$donuts[0] = "Glazed 01";
$donuts[1] = "Chocolate 02";
$donuts[2] = "Frosted 12";
$donuts[3] = "Jelly 16";

I can't seem to find a built-in function that can do this and have been racking my brain for the simplest and most efficient way to get this accomplished. Help! And thanks!

我似乎无法找到一个可以做到这一点的内置函数,并且已经用最简单,最有效的方式来完成这项工作。帮帮我!谢谢!

2 个解决方案

#1


3  

This should do the trick:

这应该是诀窍:

header('Content-Type: Text/Plain');
$donuts[0] = "Chocolate 02";
$donuts[1] = "Jelly 16";
$donuts[2] = "Glazed 01";
$donuts[3] = "Frosted 12";

print_r($donuts);

usort($donuts, function ($a, $b){
    return substr($b, -2) - substr($a, -2);
});

print_r($donuts);

NOTE

  1. To convert from highest to smallest:

    要从最高到最小转换:

    return substr($b, -2) - substr($a, -2);
    
  2. This answer make an assumption that the last 2 characters is to be used.

    这个答案假设使用最后2个字符。

UPDATE

To make it work on PHP version 5.2, change the return part to:

要使其在PHP 5.2版上运行,请将返回部分更改为:

return substr($b, strlen($b) - 2) - substr($a, strlen($a) - 2);

#2


1  

usort($donuts, function ($a, $b) {
    preg_match('/\d+$/', $a, $matchA);
    preg_match('/\d+$/', $b, $matchB);
    return $matchA[0] - $matchB[0];
});

This would of course benefit greatly from some preprocessing, so you don't need to preg_match the same strings over and over.

这当然会从一些预处理中受益匪浅,因此您不需要反复preg_match相同的字符串。

#1


3  

This should do the trick:

这应该是诀窍:

header('Content-Type: Text/Plain');
$donuts[0] = "Chocolate 02";
$donuts[1] = "Jelly 16";
$donuts[2] = "Glazed 01";
$donuts[3] = "Frosted 12";

print_r($donuts);

usort($donuts, function ($a, $b){
    return substr($b, -2) - substr($a, -2);
});

print_r($donuts);

NOTE

  1. To convert from highest to smallest:

    要从最高到最小转换:

    return substr($b, -2) - substr($a, -2);
    
  2. This answer make an assumption that the last 2 characters is to be used.

    这个答案假设使用最后2个字符。

UPDATE

To make it work on PHP version 5.2, change the return part to:

要使其在PHP 5.2版上运行,请将返回部分更改为:

return substr($b, strlen($b) - 2) - substr($a, strlen($a) - 2);

#2


1  

usort($donuts, function ($a, $b) {
    preg_match('/\d+$/', $a, $matchA);
    preg_match('/\d+$/', $b, $matchB);
    return $matchA[0] - $matchB[0];
});

This would of course benefit greatly from some preprocessing, so you don't need to preg_match the same strings over and over.

这当然会从一些预处理中受益匪浅,因此您不需要反复preg_match相同的字符串。