016——数组(十六)usort uasort uksort
<?php /*数组 usort uasort uksort */ //usort()通过自定义函数对数组进行排序,原数组索引不保留 /*$arr = array(5, 3, 7, 6, 4, 1, 2); function func($v1, $v2) { if ($v1 == $v2) return 0; return $v1 > $v2 ? 1 : -1; } $res=usort($arr, 'func'); print_r($arr);//输出:Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )*/ //uasort()通过自定义函数对数组进行排序,原数组索引保留 /*$arr = array('5' => 5, '3' => 3, '7' => 7, '6' => 6, '4' => 4, '1' => 1, '2' => 2); function func($v1, $v2) { if ($v1 == $v2) return 0; return $v1 > $v2 ? 1 : -1; } $res = @uasort($arr, 'func'); print_r($arr);//输出:Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 )*/ //uksort() 通过调用自定义函数对数组的键名进行排序。 $arr = array('9' => 5, '20' => 3, '2' => 7, '7' => 6); function func($v1, $v2) { if ($v1 == $v2) return 0; return $v1 > $v2 ? 1 : -1; //1在前,升序。1在后降序 } $res = @uksort($arr, 'func'); print_r($arr);//输出:Array ( [2] => 7 [7] => 6 [9] => 5 [20] => 3 )