对数组("1:40"、"2:30"、"6:33")从低到高进行排序?



我是PHP新手,我有一个不同格式的数组,但我不知道如何从最低到最高排序我知道像排序之类的内置功能,但这些不适合我,如果有人知道,请帮忙,我有这个数组格式的

$array = array("2:90","8:49","3:77","4:98");

这个数组需要按排序

8:49,3:77,2:90,4:98

按符号(:(后的正确值排序

您可以定义一个自定义比较器,并将usort与之一起使用:

<?php
function cmp($a, $b) {
// Split the value by the ":" delimiter and store each side into variable
list($a_first, $a_second) = explode(':', $a);
list($b_first, $b_second) = explode(':', $b);
// If the second substrings are not equal compare them
if ($a_second != $b_second) {
return strcmp($a_second, $b_second);
}
// If they are equal compare the values in the first substrings
return strcmp($a_first, $b_first);
}
$array = array("2:90","1:90","8:49","3:77","4:98");
print "Before sorting:n";
print_r($array);
usort($array, "cmp");
print "After sorting:n";
print_r($array);
?>

输出:

Before sorting: 
Array
(
[0] => 2:90
[1] => 1:90
[2] => 8:49
[3] => 3:77
[4] => 4:98
)
After sorting: 
Array
(
[0] => 8:49
[1] => 3:77
[2] => 1:90
[3] => 2:90
[4] => 4:98
)

使用的其他功能的说明和文档链接:

  • 爆炸-将字符串拆分为一个字符串
  • strcmp-二进制安全字符串比较

本答案注释中提供的处理小数的附加要求的解决方案:

<?php
function cmp($a, $b) {
// Split the value by the ":" delimiter and store each side into variable
list($a_first, $a_second) = array_map('floatval', explode(':', $a));
list($b_first, $b_second) = array_map('floatval', explode(':', $b));
// If the second substrings are not equal compare them
if (abs($a_second - $b_second) >= PHP_FLOAT_EPSILON) {
return $a_second - $b_second;
}
// If they are equal compare the values in the first substrings
return $a_first - $b_first;
}
$array = array("2:90.60","2:95.67","1:95.67","8:49","3:77.66","4:98.30");
print "Before sorting:n";
print_r($array);
usort($array, "cmp");
print "After sorting:n";
print_r($array);
?> 

输出:

Before sorting:
Array
(
[0] => 2:90.60
[1] => 2:95.67
[2] => 1:95.67
[3] => 8:49
[4] => 3:77.66
[5] => 4:98.30
)
After sorting:
Array
(
[0] => 8:49
[1] => 3:77.66
[2] => 2:90.60
[3] => 1:95.67
[4] => 2:95.67
[5] => 4:98.30
)

使用的其他功能的说明和文档链接:

  • array_map-将回调应用于给定数组的元素
  • floatval-获取变量的浮点值

最新更新