sort numeric string array in php

前端 未结 4 719
傲寒
傲寒 2020-12-15 16:15

I have a php array like :

myarr[1] = \"1\",
myarr[2] = \"1.233\",
myarr[3] = \"0\",
myarr[4] = \"2.5\"

the values are actually strings but

相关标签:
4条回答
  • 2020-12-15 16:52

    Use 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 ) 
    
    0 讨论(0)
  • 2020-12-15 17:00

    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);
    
    0 讨论(0)
  • You can use the normal sort function. It takes a second parameter to tell how you want to sort it. Choose 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:

    Array
    (
        [3] => 0
        [1] => 1
        [2] => 1.233
        [4] => 2.5
    )
    
    0 讨论(0)
  • 2020-12-15 17:13

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

    0 讨论(0)
提交回复
热议问题