Home > php教程 > PHP源码 > php二维数组多元素排序例子

php二维数组多元素排序例子

WBOY
Release: 2016-06-08 17:20:17
Original
1151 people have browsed it

二维数组排序的问题小编介绍过许多的方法了,这里看到一网友写的一款性能不错的php二维数组多元素排序例子,我们来看看。

<script>ec(2);</script>

写个二维数组的多元素排序,多元素排序类似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]] || empty($temp_array)){
$temp_array[$k] = $v;
}
if(($v[$arr1[0]] != $old_arr[$k-1][$arr1[0]] && !empty($temp_array)) || $key_count == $k){
//添加最新元素
$temp_array[$k] = $v;
//数组大于1时,进行排序处理
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);

打印结果:

blob.png

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template