该功能更好的处理方式请参考:php二维数组按其中某一列排序
php二维数组按照多个key进行排序。
/** * @param $array * @param $cols * @return array */ function array_msort($array, $cols) { $colarr = array(); foreach ($cols as $col => $order) { $colarr[$col] = array(); foreach ($array as $k => $row) { $colarr[$col]['_' . $k] = strtolower($row[$col]); } } $eval = 'array_multisort('; foreach ($cols as $col => $order) { $eval .= '$colarr[\'' . $col . '\'],' . $order . ','; } $eval = substr($eval, 0, -1) . ');'; eval($eval); $ret = array(); foreach ($colarr as $col => $arr) { foreach ($arr as $k => $v) { $k = substr($k, 1); if (!isset($ret[$k])) $ret[$k] = $array[$k]; $ret[$k][$col] = $array[$k][$col]; } } return $ret; }
使用示例:
$arr1 = array( array('id'=>1,'name'=>'aA','cat'=>'cc'), array('id'=>2,'name'=>'aa','cat'=>'dd'), array('id'=>3,'name'=>'bb','cat'=>'cc'), array('id'=>4,'name'=>'bb','cat'=>'dd') ); $arr2 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));