1. 一维数组排序
function func_sort($a,$b){
if($a == $b){
return 0;
}
return $a>$b ? -1 : 1;
}
$arr = [1,3,7,6,8];
usort($arr,'func_sort');
var_dump($arr);
输出:array(5) {
[0]=>
int(8)
[1]=>
int(7)
[2]=>
int(6)
[3]=>
int(3)
[4]=>
int(1)
}
2. 多维数组排序(根据某个值排序)
function func_array_sort($a , $b){
if($a['sort'] == $b['sort']){
return 0;
}
return $a['sort']>$b['sort'] ? -1 : 1;
}
$arr = array(['sort'=>4 , 'name'=>'red'] , ['sort'=>1 , 'name'=>'black'] , ['sort'=>2 , 'name'=>'yellow'], ['sort'=>3 , 'name'=>'bule']);
usort($arr , 'func_array_sort');
print_r($arr);
输出:Array
(
[0] => Array
(
[sort] => 4
[name] => red
)
[1] => Array
(
[sort] => 3
[name] => bule
)
[2] => Array
(
[sort] => 2
[name] => yellow
)
[3] => Array
(
[sort] => 1
[name] => black
)
)
3. 在调用对象中的方法
class Sort{
static function func_array_sort($a , $b){
if($a['sort'] == $b['sort']){
return 0;
}
return $a['sort']>$b['sort'] ? -1 : 1;
}
}
$arr = array(['sort'=>4 , 'name'=>'red'] , ['sort'=>1 , 'name'=>'black'] , ['sort'=>2 , 'name'=>'yellow'], ['sort'=>3 , 'name'=>'bule']);
usort($arr , array('Sort' , 'func_array_sort'));
print_r($arr);
输出:Array
(
[0] => Array
(
[sort] => 4
[name] => red
)
[1] => Array
(
[sort] => 3
[name] => bule
)
[2] => Array
(
[sort] => 2
[name] => yellow
)
[3] => Array
(
[sort] => 1
[name] => black
)
)