遇到这么个问题,好烦,不过官方手册还是很强大的,谢谢啦.
1 <?php 2 $testAry = array( 3 array('a' => 1, 'b' => 2, 'c' => 3), 4 array('a' => 2, 'b' => 1, 'c' => 3), 5 array('a' => 3, 'b' => 2, 'c' => 1), 6 array('a' => 1, 'b' => 3, 'c' => 2), 7 array('a' => 2, 'b' => 3, 'c' => 1), 8 array('a' => 3, 'b' => 1, 'c' => 2) 9 ); 10 11 Utility::orderBy($testAry, 'a ASC, b DESC'); 12 13 //Result: 14 $testAry = array( 15 array('a' => 1, 'b' => 3, 'c' => 2), 16 array('a' => 1, 'b' => 2, 'c' => 3), 17 array('a' => 2, 'b' => 3, 'c' => 1), 18 array('a' => 2, 'b' => 1, 'c' => 3), 19 array('a' => 3, 'b' => 2, 'c' => 1), 20 array('a' => 3, 'b' => 1, 'c' => 2) 21 ); 22 ?>
To sort an array of objects you would do something like:
Utility::orderBy($objectAry, 'getCreationDate() DESC, getSubOrder() ASC');
This would sort an array of objects that have methods getCreationDate() and getSubOrder().
Here is the function:
1 <?php 2 class Utility { 3 /* 4 * @param array $ary the array we want to sort 5 * @param string $clause a string specifying how to sort the array similar to SQL ORDER BY clause 6 * @param bool $ascending that default sorts fall back to when no direction is specified 7 * @return null 8 */ 9 public static function orderBy(&$ary, $clause, $ascending = true) { 10 $clause = str_ireplace('order by', '', $clause); 11 $clause = preg_replace('/\s+/', ' ', $clause); 12 $keys = explode(',', $clause); 13 $dirMap = array('desc' => 1, 'asc' => -1); 14 $def = $ascending ? -1 : 1; 15 16 $keyAry = array(); 17 $dirAry = array(); 18 foreach($keys as $key) { 19 $key = explode(' ', trim($key)); 20 $keyAry[] = trim($key[0]); 21 if(isset($key[1])) { 22 $dir = strtolower(trim($key[1])); 23 $dirAry[] = $dirMap[$dir] ? $dirMap[$dir] : $def; 24 } else { 25 $dirAry[] = $def; 26 } 27 } 28 29 $fnBody = ''; 30 for($i = count($keyAry) - 1; $i >= 0; $i--) { 31 $k = $keyAry[$i]; 32 $t = $dirAry[$i]; 33 $f = -1 * $t; 34 $aStr = '$a[\''.$k.'\']'; 35 $bStr = '$b[\''.$k.'\']'; 36 if(strpos($k, '(') !== false) { 37 $aStr = '$a->'.$k; 38 $bStr = '$b->'.$k; 39 } 40 41 if($fnBody == '') { 42 $fnBody .= "if({$aStr} == {$bStr}) { return 0; }\n"; 43 $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n"; 44 } else { 45 $fnBody = "if({$aStr} == {$bStr}) {\n" . $fnBody; 46 $fnBody .= "}\n"; 47 $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n"; 48 } 49 } 50 51 if($fnBody) { 52 $sortFn = create_function('$a,$b', $fnBody); 53 usort($ary, $sortFn); 54 } 55 } 56 } 57 ?>