php 根据数组中的指定键值排序,根据数组中指定键值分组
1.1 原数组如下:$person = array(
array('id'=>1,'name'=>'fj','weight'=>100,'height'=>180),
array('id&#
| 
                        
                         一、 根据数组中的指定键值排序 1.1 原数组如下:$person = array( array('id'=>1,'name'=>'fj','weight'=>100,'height'=>180), array('id'=>2,'name'=>'tom','weight'=>53,'height'=>150), array('id'=>3,'name'=>'jerry','weight'=>120,'height'=>156), array('id'=>4,'name'=>'bill','weight'=>110,'height'=>190), array('id'=>5,'name'=>'linken','weight'=>80,'height'=>200), array('id'=>6,'name'=>'madana','weight'=>95,'height'=>110), array('id'=>7,'name'=>'jordan','weight'=>70,'height'=>170) ); 1.2 排序代码 public function test($person){ $newArr = array(); foreach($person as $key=>$v){ $newArr[$key]['weight'] = $v['weight']; } array_multisort($newArr,SORT_ASC,$person);//SORT_DESC为降序,SORT_ASC为升序 dump($person); } 1.3 排序结果 array(7) {
  [0] => array(4) {
    ["id"] => int(2)
    ["name"] => string(3) "tom"
    ["weight"] => int(53)
    ["height"] => int(150)
  }
  [1] => array(4) {
    ["id"] => int(7)
    ["name"] => string(6) "jordan"
    ["weight"] => int(70)
    ["height"] => int(170)
  }
  [2] => array(4) {
    ["id"] => int(5)
    ["name"] => string(6) "linken"
    ["weight"] => int(80)
    ["height"] => int(200)
  }
  [3] => array(4) {
    ["id"] => int(6)
    ["name"] => string(6) "madana"
    ["weight"] => int(95)
    ["height"] => int(110)
  }
  [4] => array(4) {
    ["id"] => int(1)
    ["name"] => string(2) "fj"
    ["weight"] => int(100)
    ["height"] => int(180)
  }
  [5] => array(4) {
    ["id"] => int(4)
    ["name"] => string(4) "bill"
    ["weight"] => int(110)
    ["height"] => int(190)
  }
  [6] => array(4) {
    ["id"] => int(3)
    ["name"] => string(5) "jerry"
    ["weight"] => int(120)
    ["height"] => int(156)
  }
}
0.0290s 二、根据数组中指定键值分组2.1 原数组如下: $arr = [ [ 'initial' => 'A', 'typename' => '陈端'], [ 'initial' => 'F', 'typename' =>'编程' ], [ 'initial' => 'F', 'typename' => '屌丝' ] ]; 2.2 分组代码 $result = []; //初始化一个数组 foreach($arr as $k=>$v){ $result[$v['initial']][] = $v; //根据initial 进行数组重新赋值 } dump($result);//result 就是分组之后的返回值 2.3 分组结果 array(2) { ["A"] => array(1) { [0] => array(2) { ["initial"] => string(1) "A" ["typename"] => string(6) "陈端" } } ["F"] => array(2) { [0] => array(2) { ["initial"] => string(1) "F" ["typename"] => string(6) "编程" } [1] => array(2) { ["initial"] => string(1) "F" ["typename"] => string(6) "屌丝" } } } (编辑:滁州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  

