排序其值的最后几个字符数组? [英] Sort an array by the last couple characters of its values?

查看:133
本文介绍了排序其值的最后几个字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,如何也许有排序近一其价值观的字符数组?举个例子,下面的数组:

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

$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!

推荐答案

这应该做的伎俩:

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

注意


  1. 要转换从最高到最小:

  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.

    更新

    要让它在PHP 5.2版本中,将收益部分工作:

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

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

    这篇关于排序其值的最后几个字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆