作者在 2012-11-26 07:47:23 发布以下内容
sort方法
//默认排序,调用php的sort方法,失去原来的键名或索引值
$arr = A(['name'=>1,'age'=>4]);
print_r($arr->sort()); //[0=>1, 1=> 4]
//根据key排序
$arr = A(['name'=>1,'age'=>4]);
print_r($arr->sort('k')); //['age'=>4,'name'=>1]
print_r($arr->sort('-k')); //['name'=>1,'age'=>4]
//根据value排序
$arr = A(['name'=>1,'age'=>4]);
print_r($arr->sort('v')); //['name'=>1,'age'=>4]
print_r($arr->sort('-v')); //['age'=>4,'name'=>1]
//根据索引名排序,类似数据库根据字段名排序
$arr = A([['name'=>1,'age'=>4],['name'=>1,'age'=>3],['name'=>1,'age'=>2]]);
print_r($arr->sort('name,age')); //[['name'=>1,'age'=>2],['name'=>1,'age'=>3],['name'=>1,'age'=>4]];
//根据索引值排序
$arr = A([[1,4],[1,3],[1,2]]);
print_r($arr->sort('0,1')); //[[1,2],[1,3],[1,4]];
//自定义排序规则
$arr = A([1,4,2]);
$arr = $arr->sort(function($x, $y){
if($x == $y){
return 0;
}
return ($x < $y) ? -1 : 1;
});
print_r($arr); //[1,2,4]