如何将二位数组按某一个或多个字段值(升序/降序)排序?数字索引被重置,关联索引保持不变
1.$arr=array( 2. array('id'=>1,'name'=>'will','age'=>23), 3. array('id'=>2,'name'=>'myth','age'=>32), 4. array('id'=>3,'name'=>'allen','age'=>27), 5. array('id'=>4,'name'=>'martin','age'=>23) 6.); 7. 8.foreach($arr as $k=>$v){ 9. $tag1[]=$v['age']; //age排序字段 10. $tag2[]=$v['id']; //id排序字段 11.} 12.//相当于 select * from $arr order by $tag1 DESC,$tag2 ASC;//特点:$tag1、$tag2、$arr数组的元素个数必须要一致 13.array_multisort($tag1,SORT_DESC,$tag2,SORT_ASC,$arr);//根据年龄从大到小排列,年龄相同则按id升序排列 14. 15.echo "<pre>";print_r($arr);exit; 16.?> [php] view plain copy 1.<?php 2.//php二维数组如何按照指定列进行排序? 3.function arrSortByField(&$list, $field, $call_func=NULL, $sort_type=SORT_ASC){//引用传值 4. $sort_filed = array(); 5. foreach ($list as $val) { 6. if (!isset($val[$field])) return false; 7. $sort_filed[] = is_null($call_func) ? $val[$field] : call_user_func($call_func,$val[$field]); 8. } 9. return array_multisort($sort_field,$sort_type,$list);//$list顺序会随$sort_field顺序变化而变化 10.} 11. 12.$list= array( 13. array('id' =>3, 'name' => 'asdfsdf'), 14. array('id' =>1, 'name' => '12'), 15. array('id' =>4, 'name' => '10sdf'), 16. array('id' =>2, 'name' => 'ada'), 17. array('id' =>5, 'name' => 'aasdfbc') 18.); 19. 20.arrSortByField($list,'name','strlen');//按照 "name" 列的值长度进行排序 21.echo "<pre>";print_r($list); 22.arrSortByField($list,'id');//按照 "id" 列的值大小进行排序 23.echo "<pre>";print_r($list); 24. 25. 26.?>