文章来源:http://blog.sina.com.cn/s/blog_7eef675d0101fd9g.html
今天在做一个不涉及数据库的分页的时候,遇到一个按条件排序的问题,为此把解决的方案列在这里。。
PHP之所以被称之为高级语言,自然有她的妙用,就是它很多东西,早就有高手把它写好了,你只需要拿来用就行,不必自己去写方法。
所以很多人说PHP简单,其实我认为就是简单在这里,当然这只是我的个人观点。。
下面开始代码:
1、array_multisort的用法:
<?php
$arr1 = array(
'0' => array('a' => 3, 'b' => 20, 'c' => 2, 'd' => 6),
'1' => array('a' => 3, 'b' => 2, 'c' => 2, 'd' => 6),
'2' => array('a' => 3, 'b' => 22, 'c' => 2, 'd' => 6),
'3' => array('a' => 3, 'b' => 25, 'c' => 2, 'd' => 6),
'4' => array('a' => 3, 'b' => 28, 'c' => 2, 'd' => 6),
'5' => array('a' => 3, 'b' => 3, 'c' => 2, 'd' => 6),
);
$arr2 = array(
'e1' => array('a' => 3, 'b' => 20, 'c' => 2, 'd' => 6),
'e2' => array('a' => 3, 'b' => 2, 'c' => 2, 'd' => 6),
'e3' => array('a' => 3, 'b' => 22, 'c' => 2, 'd' => 6),
'e4' => array('a' => 3, 'b' => 25, 'c' => 2, 'd' => 6),
'e5' => array('a' => 3, 'b' => 28, 'c' => 2, 'd' => 6),
'e6' => array('a' => 3, 'b' => 3, 'c' => 2, 'd' => 6),
);
//提取列数组;
foreach ($arr1 as $key => $val) {
$tmp[$key] = $val['b'];
}
array_multisort($tmp,SORT_DESC,$arr1);
echo "<pre>";
print_r($arr1);
echo "</pre>";
array_multisort($tmp,SORT_DESC,$arr2);
echo "<pre>";
print_r($arr2);
echo "</pre>";
?>
2、array_sort的用法:
<?php
$arr1 = array(
'0' => array('a' => 3, 'b' => 20, 'c' => 2, 'd' => 6),
'1' => array('a' => 3, 'b' => 2, 'c' => 2, 'd' => 6),
'2' => array('a' => 3, 'b' => 22, 'c' => 2, 'd' => 6),
'3' => array('a' => 3, 'b' => 25, 'c' => 2, 'd' => 6),
'4' => array('a' => 3, 'b' => 28, 'c' => 2, 'd' => 6),
'5' => array('a' => 3, 'b' => 3, 'c' => 2, 'd' => 6),
);
$arr2 = array(
'e1' => array('a' => 3, 'b' => 20, 'c' => 2, 'd' => 6),
'e2' => array('a' => 3, 'b' => 2, 'c' => 2, 'd' => 6),
'e3' => array('a' => 3, 'b' => 22, 'c' => 2, 'd' => 6),
'e4' => array('a' => 3, 'b' => 25, 'c' => 2, 'd' => 6),
'e5' => array('a' => 3, 'b' => 28, 'c' => 2, 'd' => 6),
'e6' => array('a' => 3, 'b' => 3, 'c' => 2, 'd' => 6),
);
function array_sort($array,$keys,$type='asc'){
//$array为要排序的数组,$keys为要用来排序的键名,$type默认为升序排序
$keysvalue = $new_array = array();
//提取排序的列
foreach ($array as $k=>$v){
$keysvalue[$k] = $v[$keys];
}
if($type == 'asc'){
asort($keysvalue);//升序排列
}else{
arsort($keysvalue);//降序排列
}
//reset($keysvalue);
foreach ($keysvalue as $k=>$v){
$new_array[$k] = $array[$k];
}
return $new_array;
}
$arr = array_sort($arr1,'b','desc'); //此处对数组进行降序排列
总体的想法是这样的,要对一个多维数组按照某一个键值对排序,关键是先确定这个键值对的顺序,然后按照这个键值对的顺序去排列这个多维数组。
对于是数字索引的数组,第二种方法还是比较好的,因为它会保持数字索引,这个很好,而第一种就会把数字索引的数组重新建立数字索引;
对于是字符串索引的数组,两种方法都可以采用,完全看个人爱好。。