简体   繁体   English

错误结果 usort PHP 8

[英]Wrong result usort PHP 8

I have the following code which should sort 'BMW' to the first position:我有以下代码应该将“BMW”排序到第一个 position:

$cars=['Toyota','Volvo','BMW'];
usort($cars,function($v){return $v <=> 'BMW';});
var_export($cars);

The result with PHP7 (and smaller) is correct: PHP7(和更小)的结果是正确的:

array ( 0 => 'BMW', 1 => 'Volvo', 2 => 'Toyota', )

As far as I understand, the result with PHP8 is wrong.据我了解,PHP8 的结果是错误的。

array (0 => 'Volvo', 1 => 'BMW', 2 => 'Toyota',)

Demo: https://3v4l.org/8SCXk演示: https://3v4l.org/8SCXk

It's not up to the spaceship operator.这不取决于飞船操作员。 This one seems to be working correctly.这个似乎工作正常。 The cause must lie in the behavior of usort.原因必须在于排序的行为。

var_dump(
    'Volvo' <=> 'BMW',
    'BMW' <=> 'Volvo',
    'BMW' <=> 'Toyota',
    'Toyota' <=> 'BMW',
    'BMW' <=> 'BMW'
    );

Demo: https://3v4l.org/UaKrM演示: https://3v4l.org/UaKrM

My question: Is this a nasty bug in PHP8 or do I need to change my code?我的问题:这是 PHP8 中的一个讨厌的错误,还是我需要更改我的代码?

If you have the wrong callback function, you'll get the wrong result.如果你有错误的回调 function,你会得到错误的结果。 It should be:它应该是:

$cars = ['Toyota', 'Volvo', 'BMW'];
usort($cars, function ($a, $b) { return $a <=> $b; });
var_export($cars);

Notice the second parameter $b and how it is used.注意第二个参数$b以及它是如何使用的。

See: usort() and an example here: https://3v4l.org/X1DVU请参阅: usort()和此处的示例: https://3v4l.org/X1DVU

The difference you see with older PHP versions is indeed caused by PHP 8 switching to sable sorting, but this is irrelevant in your case.您看到的旧 PHP 版本的差异确实是由 PHP 8 切换到黑貂排序引起的,但这与您的情况无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM