php排序函数,等于mysql中的order by。

字体大小: 中小 标准 ->行高大小: 标准
<?php 
/* php 数组排序函数 
* welcome to www.caiblog.tk 
* @author caicai 
* @$array 需要排序的数组 
* @$cols 排序的关键字,相当于order by字段,传入格式为数组, 
* 比如:array('name'=>array('DESC', 'NUM'), 'cat')。 
* 当无特殊排序时(升序,不指定比较字符类型),可直接传字段,比如:'cat'; 
* 当有特殊排序是(比如降序,比如要指定比较字符类型),则需要传数组,比如:'name'=>array('DESC', 'NUM'); 
* 第一个值是排序顺序:ASC - 升序,DESC - 倒序,默认为DESC; 
* 第二个值是比较方法:NUM - 将项目按照数值比较,STR - 将项目按照字符串比较,默认为SORT_REGULAR -按照通常方法比较 
* @$len 截取数组的长度。 
*/
function array_msort($array, $cols, $len = 0) 
{ 
$colarr = array(); 
foreach($cols as $col => $order) { 
if(is_numeric($col)) { 
$col = $order; 
} 
$colarr[$col] = array(); 
foreach ($array as $k => $row) { 
$colarr[$col]['_'.$k] = strtolower($row[$col]); 
} 
} 
$params = array(); 
foreach($cols as $col => $order) { 
if(is_numeric($col)) { 
$col = $order; 
$order = array('DESC'); 
} 
if(!empty($order[0])) { 
$order[0] = $order[0] == 'ASC' ? SORT_ASC : SORT_DESC; 
} 
if(!empty($order[1])) { 
$order[1] = $order[1] == 'NUM' ? SORT_NUMERIC : $order[1] == 'STR' ? 'SORT_STRING' : SORT_REGULAR; 
} 
$params[] =& $colarr[$col]; 
$params = array_merge($params, (array)$order); 
} 
call_user_func_array('array_multisort', $params); 
$ret = array(); 
$keys = array(); 
$first = true; 
foreach($colarr as $col => $arr) { 
foreach($arr as $k => $v) { 
if($first) { 
$keys[$k] = substr($k, 1); 
} 
$k = $keys[$k]; 
if(!isset($ret[$k])) { 
$ret[$k] = $array[$k]; 
} 
$ret[$k][$col] = $array[$k][$col]; 
} 
$first = false; 
} 
return empty($len) ? $ret : array_slice($ret, 0, $len); 
} 
?>

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/67211.html