phpsortingmultidimensional-arrayfloating-pointusort

Sort Multi-dimensional array by decimal values


What I'm trying to do is sort a multi-dimensional array that contains decimal values. From what I've tested, floats are having trouble being ordered properly.

Array
(
    [0] => Array
        (
            [company] => Ebay
            [weight] => 4.6
        )

    [1] => Array
        (
            [company] => Ebay
            [weight] => 1.7
        )

    [2] => Array
        (
            [company] => Ebay
            [weight] => 3.7
        )
)


usort($array, 'order_by_weight');

// Sorts DESC highest first
function order_by_weight($a, $b) {
    return $b['weight'] - $a['weight'];
}

What is the best way to sort these numbers in descending?


Solution

  • $arr = array(
        array('company' => 'A', 'weight' => 4.6),
        array('company' => 'B', 'weight' => 1.7),
        array('company' => 'C', 'weight' => 3.7),
    );
    
    usort($arr, 'order_by_weight');
    
    function order_by_weight($a, $b) {
        return $b['weight'] > $a['weight'] ? 1 : -1;
    }
    
    var_dump($arr);
    

    PS: it's not a rocket science - this exact "trick" is used as the first example at http://php.net/usort