在 php 中排序字符串和数字

ordering strings and numbers in php

我正在试验 PHP 类型的杂耍,发现了一个我无法解释的奇怪行为。我正在根据 属性 对对象进行排序,该 属性 有时是一个字符串,有时是一个数字。使用 usort,一些项目会错位。我不知道为什么。我正在使用 PHP 7.0.16.

class Classe {
    protected $data = array();
    public function Set($chave, $valor) {
        $this->data[$chave] = $valor;
    }
    public function Get($chave) {
        return $this->data[$chave];
    }
}
$objetos = array();
$nomes = array('Joao', 'Jose', 'Lucas', 'Antonio', 'Miguel', 'Arthur', 'Davi', 'Bernardo', 'Heitor', 'Gabriel');
$posicoes = array(7, '8.2', '9', 1.0, '5', 1.1, '3.2', '2', '4', 4.2);
for ($i = 0; $i < 10; ++$i) {
    $objeto = new Classe;
    $objeto->Set('pos', $posicoes[$i]);
    $objeto->Set('nome', $nomes[$i]);
    $objetos[] = $objeto;
}
foreach ($objetos as $o) {
    echo "{$o->Get('pos')}: {$o->Get('nome')}\n";
}
echo "\nAfter sorting:\n";
usort($objetos,
    function($a, $b) {
        return $a->Get('pos') - $b->Get('pos');
    });

foreach ($objetos as $o) {
    echo "{$o->Get('pos')}: {$o->Get('nome')}\n";
}

排序后的顺序:

1: Antonio 1.1: Arthur 2: Bernardo 3.2: Davi 4: Heitor 5: Miguel 4.2: Gabriel 7: Joao 8.2: Jose 9: Lucas

注意项目 4.2 和 5 是如何乱序的。这是为什么?

我认为我们需要查看 SPL (http://php.net/manual/en/array.sorting.php) 中可用的数组排序选项。我们想使用字母数字字符按值排序,并且我们不关心 key/value 关联。这确实打开了我们的选择范围。

尝试一些其他的数组排序选项来代替 usort(...)。我必须找到一个未涵盖的排序模式。

问题是浮点值。如果你阅读 documentation 你会发现:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

并且:

Caution Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.