php二维数组多元素排序小编介绍过很多了,只是今年看到这个例子有一点区别了所以小编为各位整理了一下,希望这个排序算法能够帮助到各位.
写个二维数组的多元素排序,多元素排序类似sql中的order by sort,date,下面代码考虑性能问题,只涉及2个元素进行排序.
代码区:
-
function multipleArraySort($old_arr,$arr1,$arr2){
-
-
$old_arr = array_sort($old_arr,$arr1[0],$arr1[1]);
-
$temp_array = $new_temp_array = array();
-
foreach($old_arr as $k => $v){
-
$key_count = count($old_arr)-1;
-
-
if($v[$arr1[0]] == $old_arr[$k-1][$arr1[0]] || emptyempty($temp_array)){
-
$temp_array[$k] = $v;
-
}
-
if(($v[$arr1[0]] != $old_arr[$k-1][$arr1[0]] && !emptyempty($temp_array)) || $key_count == $k){
-
-
$temp_array[$k] = $v;
-
-
if(count($temp_array)>1){
-
if($key_count != $k){
-
-
unset($temp_array[$k]);
-
}
-
-
if($key_count != $k || $v[$arr1[0]] == $old_arr[$k-1][$arr1[0]]){
-
-
$temp_array = array_sort($temp_array,$arr2[0],$arr2[1]);
-
}
-
-
$count = count($new_temp_array)==0 ? 0 : count($new_temp_array);
-
foreach($temp_array as $val_t){
-
$new_temp_array[$count] = $val_t;
-
$count++;
-
}
-
-
$temp_array = array();
-
-
$temp_array[$k] = $v;
-
}
-
}
-
}
-
return $new_temp_array;
-
}
-
-
function array_sort($arr,$keys,$type='asc'){
-
$keysvalue = $new_array = array();
-
-
foreach ($arr as $k=>$v){
-
$keysvalue[$k] = $v[$keys];
-
}
-
-
if($type == 'asc'){
-
asort($keysvalue);
-
}else{
-
arsort($keysvalue);
-
}
-
reset($keysvalue);
-
$count_s = 0;
-
-
foreach ($keysvalue as $k=>$v){
-
$new_array[$count_s] = $arr[$k];
-
$count_s++;
-
}
-
return $new_array;
-
}
调用方法:
-
$old_arr = array(
-
array('id'=>1,'sort'=>1,'date'=>'1405648791'),
-
array('id'=>2,'sort'=>1,'date'=>'1405649791'),
-
array('id'=>3,'sort'=>2,'date'=>'1405647791'),
-
);
-
$arr1 = array('sort','desc');
-
$arr2 = array('date','desc');
-
$newArr = multipleArraySort($old_arr,$arr1,$arr2);
-
var_dump($newArr);