1. 云栖社区>
2. PHP教程>
3. 正文

# PHP排序函数实例集绵usort uksort uasort

``\$arr=["a"=>4,"b"=>2,"c"=>8,"d"=>"6"];sort(\$arr);echo "<pre>";print_r(\$arr);Array(    [0] => 2    [1] => 4    [2] => 6    [3] => 8)   ``

ksort() 按照键名（key）对关联数组进行升序排序；

``\$arr=["a"=>4,"b"=>2,"c"=>8,"d"=>"6"];ksort(\$arr);echo "<pre>";print_r(\$arr);``

``Array(    [a] => 4    [b] => 2    [c] => 8    [d] => 6)``

``function my_sort(\$a,\$b){  //返回 0 -1 1if (\$a['key1']==\$b['key1']) return 0;return (\$a['key1']<\$b['key1'])?-1:1; }\$arr = [    ['key1' => 10, 'key2' => 'linux'],    ['key1' => 20, 'key2' => 'mysql'],    ['key1' => 9, 'key2' => 'php']];usort(\$arr, 'my_sort'); //自定义函数  usort 根据数值进行排序，但并不会保存关键字echo "<pre>";print_r(\$arr);``
``Array(    [0] => Array        (            [key1] => 9            [key2] => php        )    [1] => Array        (            [key1] => 10            [key2] => linux        )    [2] => Array        (            [key1] => 20            [key2] => mysql        ))``
``uksort(\$arr, 'my_sort');  //排序将基于关键字echo "<pre>";print_r(\$arr);Array(    [2] => Array        (            [key1] => 9            [key2] => php        )    [1] => Array        (            [key1] => 20            [key2] => mysql        )    [0] => Array        (            [key1] => 10            [key2] => linux        ))uasort(\$arr, 'my_sort');  //uasort 关键字就会被保存echo "<pre>";print_r(\$arr);Array(    [2] => Array        (            [key1] => 9            [key2] => php        )    [0] => Array        (            [key1] => 10            [key2] => linux        )    [1] => Array        (            [key1] => 20            [key2] => mysql        ))``

usort uasort uksort 根据二维数组排序，并且usort uasort根据值排序，uasort保留本身键名，uksort根据键名排序

40+云计算产品，6个月免费体验