基于元素内的数值按数字顺序对数组进行排序

时间:2014-05-21 01:14:52

标签: php arrays

如何根据元素中的数值按数字顺序对数组进行排序:元素是字符串?

例如。从:

Array(
0 => One:3 
1 => Two:1
2 => Three:4
3 => Four:2
)

为:

Array(
    0 => Two:1
    1 => Four:2
    2 => One:3
    3 => Three:4
    )

2 个答案:

答案 0 :(得分:1)

给出你的输入数组:

$arr = array('One:3','Two:1','Three:4','Four:2');
usort($arr, function($a, $b) {
  return filter_var($a, FILTER_SANITIZE_NUMBER_INT) - filter_var($b, FILTER_SANITIZE_NUMBER_INT);
});
print_r($arr);

输出:

Array
(
    [0] => Two:1
    [1] => Four:2
    [2] => One:3
    [3] => Three:4
)

答案 1 :(得分:0)

如果你的字符串遵循这种模式,你可以使用uasort()函数并构建一个对其进行排序的函数。例如:

$elements = array('One:3','Two:1','Three:4','Four:2');

uasort($elements, function($a, $b){
    $a = array_pop(explode(':', $a));
    $b = array_pop(explode(':', $b));

    if ($a == $b) {
        return 0;
    }

    return ($a < $b) ? -1 : 1;
});

print_r($elements); // Array ( [1] => Two:1 [3] => Four:2 [0] => One:3 [2] => Three:4 )