PHP数组同值稳定排序

在 PHP 中对数组排序有很多函数,如 sort, asort, arsort, ksort, krsort, uasort 等等,但是有一个问题,如一个数组:

$test = array(1 => 0, 99 => 0, 87 => 0, 45 => 0, 67 => 0, 11 => 1, 2 => 0);

$test = array(1 => 0, 99 => 0, 87 => 0, 45 => 0, 67 => 0, 11 => 1, 2 => 0);

用 asort 函数对其进行排序,asort($test) 结果如下(转换为 json 格式):

{"67":0,"2":0,"1":0,"45":0,"87":0,"99":0,"11":1}

{"67":0,"2":0,"1":0,"45":0,"87":0,"99":0,"11":1}

可以看到排序虽然正确,值为 1 的元素排到后面去了,但是值为 0 的元素顺序跟以前不一样了,如何保证 PHP 数组同值元素排序后顺序保持不变呢?

感谢网友的回答:

PHP 的 asort 和 sort,底层是用快排实现的。无法保证同等大小的元素的顺序。要保证值为0的顺序不变?只能自己实现一个数组排序。对于数组中相等的元素,它们在排序后的顺序是未定义的。 (也即相等元素之间的顺序是不稳定的)

解决方法

1.在 PHP 官方手册上其实有答案了,直接贴出来:

If you want to keep the order when two members compare as equal, use this.

function stable_uasort(&$array, $cmp_function) {

    if(count($array) < 2) {

        return;

    }

    $halfway = count($array) / 2;

    $array1 = array_slice($array, 0, $halfway, TRUE);

    $array2 = array_slice($array, $halfway, NULL, TRUE);

    stable_uasort($array1, $cmp_function);

    stable_uasort($array2, $cmp_function);

    if(call_user_func($cmp_function, end($array1), reset($array2)) < 1) {

        $array = $array1 + $array2;

        return;

    }

    $array = array();

    reset($array1);

    reset($array2);

    while(current($array1) && current($array2)) {

        if(call_user_func($cmp_function, current($array1), current($array2)) < 1) {

            $array[key($array1)] = current($array1);

            next($array1);

        } else {

            $array[key($array2)] = current($array2);

            next($array2);

        }

    }

    while(current($array1)) {

        $array[key($array1)] = current($array1);

        next($array1);

    }

    while(current($array2)) {

        $array[key($array2)] = current($array2);

        next($array2);

    }

    return;

}

function cmp($a, $b) {

    if($a['n'] == $b['n']) {

        return 0;

    }

    return ($a['n'] > $b['n']) ? -1 : 1;

}

$a = $b = array(

    'a' => array("l" => "A", "n" => 1),

    'b' => array("l" => "B", "n" => 2),

    'c' => array("l" => "C", "n" => 1),

    'd' => array("l" => "D", "n" => 2),

    'e' => array("l" => "E", "n" => 2),

);

uasort($a, 'cmp');

print_r($a);

stable_uasort($b, 'cmp');

print_r($b);
  1. 如果使用 Composer,也可以使用 PHP 扩展包,这里有一个扩展包 vanderlee/php-stable-sort-functions 就是专门解决这个问题的。

bool StableSort::arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

bool StableSort::asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

bool StableSort::natcasesort ( array &Sarray )

bool StableSort::natsort ( array &Sarray )

bool StableSort::uasort ( array &$array , callable $value_compare_func )

bool StableSort::uksort ( array &$array , callable $value_compare_func )

bool StableSort::usort ( array &$array , callable $value_compare_func )

推荐链接

扩展包地址:https://packagist.org/packages/vanderlee/php-stable-sort-functions

https://segmentfault.com/q/1010000007492504?_ea=1362649

你可能感兴趣的:(PHP数组同值稳定排序)