数组按字值排序

时间:2019-05-21 14:01:22

标签: php arrays sorting multidimensional-array

我想按升序对值进行排序。

我尝试了ksort和其他排序示例。

Array
(
    [0] => stdClass Object
        (
            [tenure] => 1 year to less than 2 years
        )

    [1] => stdClass Object
        (
            [tenure] => 10 years to less than 15 years
        )

    [2] => stdClass Object
        (
            [tenure] => 15 years or more
        )

    [3] => stdClass Object
        (
            [tenure] => 2 years to less than 5 years
        )

    [4] => stdClass Object
        (
            [tenure] => 5 years to less than 10 years
        )

)

我想对上述数组的权属值进行排序。

3 个答案:

答案 0 :(得分:2)

由于所有值均以数字开头,因此您可以将它们转换为整数并使用usort对它们进行排序:

usort($array, function ($a, $b) { return (int)$a->tenure - (int)$b->tenure; });
print_r($array);

输出:

Array (
  [0] => stdClass Object (
    [tenure] => 1 year to less than 2 years
  )
  [1] => stdClass Object (
    [tenure] => 2 years to less than 5 years
  )
  [2] => stdClass Object (
    [tenure] => 5 years to less than 10 years
  )
  [3] => stdClass Object (
    [tenure] => 10 years to less than 15 years
  )
  [4] => stdClass Object (
    [tenure] => 15 years or more
  )
)

Demo on 3v4l.org

答案 1 :(得分:2)

您可以使用核心array_multisort

array_multisort(array_column($array, 'tenure'),   
SORT_ASC, SORT_NATURAL, $array);

https://3v4l.org/cXNQH

答案 2 :(得分:1)

您可以使用array_walkksort,也可以将object更改为array

$arr = (array) $object;

然后尝试这个

$res=[];
array_walk($arr, function($v, $k) use (&$res){
  $key = substr($v['tenure'], 0, strspn($v['tenure'], "0123456789"));
  $res[$key] = $v;
});
ksort($res);

Working Demo