滔哥原创
/* _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---‘\____ .‘ \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ‘‘\---/‘‘ | | \ .-\__ `-` ___/-. / ___`. .‘ /--.--\ `. . __ ."" ‘< `.___\_<|>_/___.‘ >‘"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-‘====== `=---=‘ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 佛祖保佑 永无BUG */ array(array(),array()); $arr1=array(array(‘itemid‘=> 226,‘title‘=> ‘四中附近有一大厅出租‘,‘edittime‘=> 1409387090), array(‘itemid‘=> 311,‘title‘=> ‘四中西邻文华园小区楼房出租‘,‘edittime‘=> 1409272174), array(‘itemid‘=> 312,‘title‘=> ‘四中西邻文华园小区楼房出租2‘,‘edittime‘=> 1409272074), array(‘itemid‘=> 313,‘title‘=> ‘四中西邻文华园小区楼房出租3‘,‘edittime‘ => 1409271174) ); $arr2=array(array(‘itemid‘=> 226,‘title‘=> ‘四中附近有一大厅出租12‘,‘edittime‘=> 1409287090), array(‘itemid‘=> 314,‘title‘=> ‘四中西邻文华园小区楼房出租12‘,‘edittime‘=> 1409172174), array(‘itemid‘=> 310,‘title‘=> ‘四中西邻文华园小区楼房出租312‘,‘edittime‘ => 1309271174) ); $b=mylist(array_merge($arr1,$arr2)); print_r($b); function mylist($array){ $arr=array(); $list=array(); foreach($array as $v){ $arr[$v[‘itemid‘]]=$v[‘edittime‘]; $list[$v[‘itemid‘]]=$v; } arsort($arr); $newarr=array(); foreach($arr as $k=>$v){ $newarr[]=$list[$k]; } return $newarr; }
本人需求更改
/** * 按照指定键名对二维数组排序 * $array 传过来的数组 * $key 指定的键名 * $type 指定的排序类型 asc 升序,desc 降序 */ function orderArray($array = array() ,$key = ‘id‘, $type = ‘asc‘) { $arr = array(); $list = array(); foreach($array as $v){ $arr[$v[$key]] = $v[$key]; $list[$v[$key]] = $v; } if($type == ‘asc‘){ asort($arr); }else{ arsort($arr); } $newarr =array(); foreach($arr as $k => $v){ $newarr[] =$list[$k]; } return $newarr; }
/** * 冒泡排序,如果二维数组中的元素不一致,可以使用次方法 add by wangt * $arr 要排序的数组 * $key 指定要排序的字段 */ function interpretSort( $arr = array() ,$key = ‘order‘) { $count = count($arr); if( $count <= 0 ) return false; for( $i = 0; $i < $count; $i ++ ){ for( $j = $count - 1; $i < $j; $j --){ if( $arr[$j][$key] < $arr[$j-1][$key] ){ //交换相邻位置的值 $tmp = $arr[$j]; $arr[$j] = $arr[$j-1]; $arr[$j-1] = $tmp; } } } return $arr; }
简单的二维数组按照指定字段排序
echo "<pre>"; $arr=array( ‘aaa‘=>array( ‘age‘=>32, ‘name‘=>‘张三‘ ), ‘bbb‘=>array( ‘age‘=>12, ‘name‘=>‘李四‘ ), ‘ccc‘=>array( ‘age‘=>25, ‘name‘=>‘赵六‘ ) ); function paixu($a,$b){ return $b[‘age‘]-$a[‘age‘]; } uasort($arr,‘paixu‘); print_r($arr);
要排序的key 有重复值
function RorderArray( $array = [], $key = ‘‘, $order = ‘asc‘ ){ $sort = $order == ‘asc‘ ? ‘SORT_ASC‘ : ‘SORT_DESC‘; $arrSort = array(); foreach($array AS $uniqid => $row){ foreach($row AS $k=>$value){ $arrSort[$k][$uniqid] = $value; } } array_multisort($arrSort[$key], constant($sort), $array); return $array; }
时间: 2024-11-10 17:14:57