usort差异php7.1 vs php5.6 [英] usort difference php7.1 vs php5.6

查看:75
本文介绍了usort差异php7.1 vs php5.6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将项目从php5.6迁移到php7.1.大部分进展顺利,但我只是一堵墙就碰壁了.

I'm currently migrating a project from php5.6 to php7.1. Most is going well, but I just hit a wall one one test.

函数usort在两个版本上都没有相同的行为,并且似乎没有记录在案(不是两个值相等,然后顺序未定义).在我的测试案例中,返回的数组顺序是相反的.

The function usort doesn't have the same behavior on both version, and it doesn't seem to be documented (it's not that two values are equals and then the order is undefined). In my test case, the returned array order is reversed.

这是问题的重现.请注意,为了简化起见,我一直都返回-1(这里重点介绍PHP5.6和7之间的差异)

Here is a reproduction of the problem. Note that I return -1 all the time for simplification (I'm focusing in the diff between PHP5.6 and 7 here)

代码在两个版本上运行:

Code run on both versions:

$a = [['value' => 1, 'toto' => 'toto'], ['value' => 1, 'toto' => null]];
usort($a, function ($a, $b) { return -1;});
print_r($a);

PHP 5.6的结果:

Results in PHP 5.6:

Array
(
    [0] => Array
        (
            [value] => 1
            [toto] =>
        )

    [1] => Array
        (
            [value] => 1
            [toto] => toto
        )

)

PHP 7.1

Array
(
    [0] => Array
        (
            [value] => 1
            [toto] => toto
        )

    [1] => Array
        (
            [value] => 1
            [toto] =>
        )

)

推荐答案

这样做的原因是,在这种情况下,值将根据PHP版本以不同的顺序传递给usort()回调.

The reason for this is that in this case the values get passed to the usort() callback in different order depending on the PHP version.

https://3v4l.org/bW5WP

$array = ['a', 'b'];
usort($array, function ($firstValue, $secondValue) { echo "COMPARING: {$firstValue} with {$secondValue}\n"; return -1;});

PHP 5.6输出:

PHP 5.6 output:

比较:b与a

COMPARING: b with a

PHP 7.x输出:

PHP 7.x output:

比较:a与b

COMPARING: a with b

这与实际比较给定值的回调无关紧要.但是,您的回调总是会返回-1,这意味着第一个值小于第二个值.在PHP 5.6中,这导致b在列表中排在第一位,在PHP 7.x中,a将在列表中排在第一.

This doesn't matter to callbacks which actually compare the given values. Your callback however always returns -1, which means first value is lesser than the second value. In PHP 5.6 this results in b being first in the list, in PHP 7.x a will be first.

如果您的回调函数对两个以上值的数组进行排序,则从回调函数返回令人反感的结果将导致未定义的行为.

Returning incosistent results from the callback will result in undefined behavior if your callback is sorting an array of more than 2 values.

这篇关于usort差异php7.1 vs php5.6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆