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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:52:20  来源:igfitidea点击:

sort numeric string array in php

phparrays

提问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 sortfunction. 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

Use natsort()

使用natsort()

$myarr[1] = "1";
$myarr[2] = "1.233";
$myarr[3] = "0";
$myarr[4] = "2.5";

natsort($myarr);
print_r($myarr);

Output:

输出:

Array ( [2] => 0 [0] => 1 [1] => 1.233 [3] => 2.5 ) 

回答by kovshenin

Use the php usortfunction and in your callback function convert your strings to floats to compare them.

使用 php usort函数并在回调函数中将字符串转换为浮点数以进行比较。

回答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);