1 <?php 2 /** 3 * 二维数组根据某个字段排序 4 * 功能:按照用户的年龄倒序排序 5 * @author ruxing.li 6 */ 7 header(‘Content-Type:text/html;Charset=utf-8‘); 8 $arrUsers = array( 9 array( 10 ‘id‘ => 1, 11 ‘name‘ => ‘张三‘, 12 ‘age‘ => 25, 13 ), 14 array( 15 ‘id‘ => 2, 16 ‘name‘ => ‘李四‘, 17 ‘age‘ => 23, 18 ), 19 array( 20 ‘id‘ => 3, 21 ‘name‘ => ‘王五‘, 22 ‘age‘ => 40, 23 ), 24 array( 25 ‘id‘ => 4, 26 ‘name‘ => ‘赵六‘, 27 ‘age‘ => 31, 28 ), 29 array( 30 ‘id‘ => 5, 31 ‘name‘ => ‘黄七‘, 32 ‘age‘ => 20, 33 ), 34 ); 35 36 37 $sort = array( 38 ‘direction‘ => ‘SORT_DESC‘, //排序顺序标志 SORT_DESC 降序;SORT_ASC 升序 39 ‘field‘ => ‘age‘, //排序字段 40 ); 41 $arrSort = array(); 42 foreach($arrUsers AS $uniqid => $row){ 43 foreach($row AS $key=>$value){ 44 $arrSort[$key][$uniqid] = $value; 45 } 46 } 47 if($sort[‘direction‘]){ 48 array_multisort($arrSort[$sort[‘field‘]], constant($sort[‘direction‘]), $arrUsers); 49 } 50 51 var_dump($arrUsers); 52 53 /* 54 输出结果: 55 56 array (size=5) 57 0 => 58 array (size=3) 59 ‘id‘ => int 5 60 ‘name‘ => string ‘黄七‘ (length=6) 61 ‘age‘ => int 20 62 1 => 63 array (size=3) 64 ‘id‘ => int 2 65 ‘name‘ => string ‘李四‘ (length=6) 66 ‘age‘ => int 23 67 2 => 68 array (size=3) 69 ‘id‘ => int 1 70 ‘name‘ => string ‘张三‘ (length=6) 71 ‘age‘ => int 25 72 3 => 73 array (size=3) 74 ‘id‘ => int 4 75 ‘name‘ => string ‘赵六‘ (length=6) 76 ‘age‘ => int 31 77 4 => 78 array (size=3) 79 ‘id‘ => int 3 80 ‘name‘ => string ‘王五‘ (length=6) 81 ‘age‘ => int 40 82 83 */
时间: 2024-11-04 02:26:40