usort issue with decimal numbers

前端 未结 3 2024
醉酒成梦
醉酒成梦 2020-12-05 11:41

I\'m currently trying to sort a multidimensional array by its subvalues. The structure of the array is:

[0] => Array
    (
        [id] => 87
        [         


        
相关标签:
3条回答
  • 2020-12-05 12:41

    Try strnatcmp():

    usort($output, function($a, $b) {
        return strnatcmp($b->days_left, $a->days_left);
    });
    
    0 讨论(0)
  • 2020-12-05 12:42

    The PHP doc has a comment that has the solution to this problem. A big thanks to that guy.

    Here is a function to sort multidimensional arrays with decimal numbers :

    function usortWithFloatVals() {
        $arguments = func_get_args();
        $array = $arguments[0];
        $code = '';
        for ($c = 1; $c < count($arguments); $c += 2) {
            if (in_array($arguments[$c + 1], array("ASC", "DESC"))) {
                $code .= 'if ($a["'.$arguments[$c].'"] != $b["'.$arguments[$c].'"]) {';
                if ($arguments[$c + 1] == "ASC") {
                    $code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? -1 : 1); }';
                }
                else {
                    $code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? 1 : -1); }';
                }
            }
        }
        $code .= 'return 0;';
        $compare = create_function('$a,$b', $code);
        usort($array, $compare);
        return $array;
    }
    

    Use it just like how you use usort() :

    usortWithFloatVals($data, function($a, $b) {
        return ($a[$_GET['sortby']] - $b[$_GET['sortby']]) ? 1 : -1;
    });
    
    0 讨论(0)
  • 2020-12-05 12:46

    See usort docs. Float result will be converted to integer. For correct work use this code:

    usort(
        $data, 
        function($a, $b) {
            $result = 0;
            if ($a[$_GET['sortby']] > $b[$_GET['sortby']]) {
                $result = 1;
            } else if ($a[$_GET['sortby']] < $b[$_GET['sortby']]) {
                $result = -1;
            }
            return $result; 
        }
    );
    
    0 讨论(0)
提交回复
热议问题