php 在php中对数字字符串数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4075896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort numeric string array in php
提问by Prashant
I have a php array like :
我有一个 php 数组,如:
myarr[1] = "1",
myarr[2] = "1.233",
myarr[3] = "0",
myarr[4] = "2.5"
the values are actually strings but i want this array to be sorted numerically, also considering float values and maintaining index association.
这些值实际上是字符串,但我希望这个数组按数字排序,同时考虑浮点值和维护索引关联。
Please help me out. Thanks
请帮帮我。谢谢
回答by Felix Kling
You can use the normal sort
function. It takes a second parameter to tell how you want to sort it. Choose SORT_NUMERIC
.
您可以使用普通sort
功能。它需要第二个参数来告诉您要如何对其进行排序。选择SORT_NUMERIC
。
Example:
例子:
sort($myarr, SORT_NUMERIC);
print_r($myarr);
prints
印刷
Array
(
[0] => 0
[1] => 1
[2] => 1.233
[3] => 2.5
)
Update: For maintaining key-value pairs, use asort
(takes the same arguments), example output:
更新:为了维护键值对,使用asort
(采用相同的参数),示例输出:
Array
(
[3] => 0
[1] => 1
[2] => 1.233
[4] => 2.5
)
回答by Alex Pliutau
回答by kovshenin
回答by jwueller
You can convert your strings to real numbers (floats) and sort them afterwards:
您可以将字符串转换为实数(浮点数)并在之后对它们进行排序:
foreach ($yourArray as $key => $value) {
$yourArray[$key] = floatval($value);
}
sort($yourArray, SORT_NUMERIC);