php 二维数组的分组排序实现代码
分组排序,代码如下:
- <?php
- $new2['group']['key']='time';
- $new['aa']['b']=44;
- $new['aa']['c']=33;
- $new['aa']['d']=34;
- $new['bb']['b']=55;
- $new['bb']['c']=32;
- $new['cc']['4']=77;
- $new['dd']['g']=55;
- $new['dd']['c']=54;
-
- function arr_group_sort($new){
- foreach($new as $key=>$val){
- asort($new[$key]);
- $tmp=$new[$key];
- $tmp[]=$key;
- $a=array_shift($new[$key]);
- $aa[$a]=$tmp;
- ksort($aa);
- }
- foreach($aa as $key=>$val){
- $b=array_pop($aa[$key]);
- $bb[$b]=$aa[$key];
- }
- return $bb;
- }
-
- $c=arr_group_sort($new);
- print_r($new);
- print_r($c);
- ?>
其它的二维数组排序的方法,代码如下:
- 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);
- foreach ($keysvalue as $k=>$v){
- $new_array[$k] = $arr[$k];
- }
- return $new_array;
- }
它可以对二维数组按照指定的键值进行排序,也可以指定升序或降序排序法(默认为升序),用法示例如下:
- $array = array(
- array('name'=>'手机','brand'=>'诺基亚','price'=>1050),
- array('name'=>'笔记本电脑','brand'=>'lenovo','price'=>4300),
- array('name'=>'剃须刀','brand'=>'飞利浦','price'=>3100),
- array('name'=>'跑步机','brand'=>'三和松石','price'=>4900),
- array('name'=>'手表','brand'=>'卡西欧','price'=>960),
- array('name'=>'液晶电视','brand'=>'索尼','price'=>6299),
- array('name'=>'激光打印机','brand'=>'惠普','price'=>1200)
- );
-
- $ShoppingList = array_sort($array,'price');
- print_r($ShoppingList);