我想按升序对值进行排序。
我尝试了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
)
)
我想对上述数组的权属值进行排序。
答案 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
)
)
答案 1 :(得分:2)
您可以使用核心array_multisort
array_multisort(array_column($array, 'tenure'),
SORT_ASC, SORT_NATURAL, $array);
答案 2 :(得分:1)
您可以使用array_walk
,ksort
,也可以将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);