PHP中的usort() 函数是非稳定排序怎么办?

WBOY
Release: 2016-06-20 12:28:46
Original
1645 people have browsed it

项目有个需求
一组数据,先按参数1进行排序,参数1相同的,再按参数2进行排序。
如果usort是稳定排序的话,直接用usort把数组按参数2进行排序,再把排序后的数组按参数1进行排序。
但是经过试验,usort竟然是不稳定排序,怎么办?
代码如下:

<?php$a1 = array('key1'=>1,'key2'=>1);$a2 = array('key1'=>2,'key2'=>2);$a3 = array('key1'=>2,'key2'=>3);$a = array($a3,$a2,$a1);usort($a,"my_sort2");print_r($a);usort($a,"my_sort1");print_r($a);function my_sort1($a,$b){if ($a['key1']==$b['key1']) return 0;return ($a['key1']<$b['key1'])?-1:1;}function my_sort2($a,$b){if ($a['key2']==$b['key2']) return 0;return ($a['key2']<$b['key2'])?-1:1;}?>
Copy after login

输出如下:
Array(    [0] => Array        (            [key1] => 1            [key2] => 1        )    [1] => Array        (            [key1] => 2            [key2] => 2        )    [2] => Array        (            [key1] => 2            [key2] => 3        ))Array(    [0] => Array        (            [key1] => 1            [key2] => 1        )    [1] => Array        (            [key1] => 2            [key2] => 3        )    [2] => Array        (            [key1] => 2            [key2] => 2        ))
Copy after login

这种情况下,只能自己写个插入排序之类的稳定排序算法了吗?


回复讨论(解决方案)

$a1 = array('key1'=>1,'key2'=>1);$a2 = array('key1'=>2,'key2'=>2);$a3 = array('key1'=>2,'key2'=>3);$a = array($a3,$a2,$a1);foreach($a as $v) {  $r2[] = $v['key2'];  $r1[] = $v['key1'];}array_multisort($r1,$r1, $a);print_r($a);
Copy after login
Array(    [0] => Array        (            [key1] => 1            [key2] => 1        )    [1] => Array        (            [key1] => 2            [key2] => 2        )    [2] => Array        (            [key1] => 2            [key2] => 3        ))
Copy after login

多维数组排序用这个array_multisort
http://php.net/manual/zh/function.array-multisort.php

<?php$a1 = array('key1'=>1,'key2'=>1);$a2 = array('key1'=>2,'key2'=>2);$a3 = array('key1'=>2,'key2'=>3);$a = array($a3,$a2,$a1);foreach($a as $v){     $ar1[] = $v['key1'];     $ar2[] = $v['key2'];}array_multisort($ar1,SORT_ASC,$ar2,SORT_ASC, $a);print_r($a);?>
Copy after login



Array
(
    [0] => Array
        (
            [key1] => 1
            [key2] => 1
        )

    [1] => Array
        (
            [key1] => 2
            [key2] => 2
        )

    [2] => Array
        (
            [key1] => 2
            [key2] => 3
        )

)

多谢两位指点 @xuzuning @傲雪星枫 

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!