我尝试了几种排序功能,并在互联网上搜索了很长时间。但没有任何答案。
我在PHP中有一个数组,如下所示:
$array = array('Real life (100%)', 'Computer Games (19%)', 'Sport in Freetime (34%)');
现在我想用数字对这个数组进行排序。像:
array(
[1] => 'Real life (100%)'
[2] => 'Sport in Freetime (34%)'
[3] => 'Computer Games (19%)'
)
有办法做到这一点吗?
答案 0 :(得分:0)
使用usort
和filter_var函数的解决方案:
$arr = ['Real life (100%)', 'Computer Games (19%)', 'Sport in Freetime (34%)'];
usort($arr, function($a,$b){
return filter_var($b, FILTER_SANITIZE_NUMBER_INT) - filter_var($a, FILTER_SANITIZE_NUMBER_INT);
});
print_r($arr);
输出:
Array
(
[0] => Real life (100%)
[1] => Sport in Freetime (34%)
[2] => Computer Games (19%)
)