1. 程式人生 > >PHP二維陣列根據指定鍵排序

PHP二維陣列根據指定鍵排序

//對二維陣列進行排序的函式
/** 引數說明
$arrays:
    排序的陣列。
$sort_key:
    排序的鍵。
$sort_order:
    SORT_ASC - 預設,按升序排列。(A-Z)
    SORT_DESC - 按降序排列。(Z-A)
$sort_type:
    SORT_REGULAR - 預設 將每一項按常規順序排列。
    SORT_NUMERIC - 將每一項按數字順序排列。
    SORT_STRING - 將每一項按字母順序排列。
*/
function umember_sort($arrays,$sort_key,$sort_order=SORT_DESC,$sort_type=SORT_NUMERIC ){   
    if(is_array($arrays)){   
        foreach ($arrays as $array){   
            if(is_array($array)){   
                $key_arrays[] = $array[$sort_key];   //將排序的鍵存進陣列
            }else{   
                return false;   
            }   
        }   
    }else{   
        return false;   
    }  

    //運用PHP自帶函式將鍵的陣列排序並返回排序後的陣列
    array_multisort($key_arrays,$sort_order,$sort_type,$arrays);   
    return $arrays;   
} 


//需要排序的陣列資料
$data = array(
    array(
      'account' => 'zhaoxing7',
      'uid' => '306019',
      'password' => 'kw23yt',
      'username' => '趙dsf1',
      'heartbeat' => '5' ,
      'gpscycle' => '30' ,
      'level' => '1' ,
      'lasttime' => '2018-07-13 14:11:01' ,
      'num' =>'dfg',
      'note' => '工程隊隊員a',
    ),
    array (
      'account' => 'zxg5',
      'uid' => '306017' ,
      'password' => 'kw23yt',
      'username' => '趙sfe7',
      'heartbeat' => '5' ,
      'gpscycle' => '30' ,
      'level' => '1' ,
      'lasttime' => '2018-07-13 14:11:01' ,
      'num' =>'dfg',
      'note' => '工程隊隊員s',
    ),
    array (
      'account' => 'zhaoxing3',
      'uid' => '306015',
      'password' => 'kw23yt',
      'username' => '趙sf7',
      'heartbeat' => '5' ,
      'gpscycle' => '30' ,
      'level' => '1' ,
      'lasttime' => '2018-07-13 14:11:01' ,
      'num' =>'dfg',
      'note' => '工程隊隊員7',
    ),
    array (
      'account' => 'fdgdfgf',
      'uid' => '306034',
      'password' => 'kwd3yt',
      'username' => '趙sdf7',
      'heartbeat' => '5' ,
      'gpscycle' => '30' ,
      'level' => '1' ,
      'lasttime' => '2018-07-13 14:11:01' ,
      'num' =>'dfg',
      'note' => '工程隊隊員7',
    ),
    array (
      'account' => 'dsfdsf',
      'uid' => '306023' ,
      'password' => 'kd3yt',
      'username' => '趙dd7',
      'heartbeat' => '5' ,
      'gpscycle' => '30' ,
      'level' => '1' ,
      'lasttime' => '2018-07-13 14:11:01' ,
      'num' =>'dfg',
      'note' => '工程隊隊員6',
    ),
    array (
      'account' => 'zhaoxing1',
      'uid' => '306013',
      'password' => 'kd3yt',
      'username' => 'sfdd7',
      'heartbeat' => '5' ,
      'gpscycle' => '30' ,
      'level' => '1' ,
      'lasttime' => '2018-07-13 14:11:01' ,
      'num' =>'dfg',
      'note' => '工程隊隊員7',
    )
);


//呼叫函式,傳入需要排序的陣列,並指定排序的鍵(此處以uid降序排序),返回排序後的二維陣列 
$data = umember_sort($data,'uid');