總結幾個介面中常用的方法
阿新 • • 發佈:2018-12-10
/** * 構建返回頭資訊 */ private function buildHeader($retCode, $retMessage) { $retNode = new stdClass(); $retNode->retCode = $retCode; $retNode->retMessage = $retMessage; return $retNode; } /** * 成功返回資訊 */ function success($body) { $head = $this->buildHeader(200, '成功'); $ret = array( 'Head'=>$head, 'Body'=>$body, ); return json_encode($ret); } /** * 失敗返回資訊 */ function failed($retCode, $retMessage) { $head = $this->buildHeader($retCode, $retMessage); $ret = array( 'Head'=>$head, 'Body'=>array(), ); return json_encode($ret); } /** * 構建成功提示資訊 */ function buildFakeStatus($Message) { $retNode = new stdClass(); $retNode->Checked=1; $retNode->Message=$Message; return $retNode; } /** * post 接值 * @param string post名稱 * @must bool true 不能為空值 */ function getPostString($param, $must=false) { $value = $_POST[$param]; if($must == true) { if($value=="") { throw new Exception("$param 引數不能為空"); } } return $value; } /** * 封包輸出,確保輸出之前,將輸出格式設定為json格式 */ function printJson($packageData) { header('Content-type: application/json'); print $packageData; } /** * 通用介面卡 */ function adapter($params, $node) { $ret = new StdClass(); foreach($params as $key=>$value) { $part = $node; $sections = explode('/', $key); foreach($sections as $section) { $part = $part[$section]; } if(isset($part)) { $ret->$value = $part; } else { $ret->$value = NULL; } } return $ret; } /* * 去除null 變成 '' * */ function removeNull($str){ return $string=$str==null?'':$str; } /** * 根據陣列的某個欄位排序 * */ function arrSort($data,$field,$direction='DESC'){ if($direction=='asc'||$direction=='ASC'){ $direction='SORT_ASC'; }else{ $direction='SORT_DESC'; } $sort = array( 'direction' => $direction, //排序順序標誌 SORT_DESC 降序;SORT_ASC 升序 'field' => $field, //排序欄位 ); $arrSort = array(); foreach($data AS $uniqid => $row){ foreach($row AS $key=>$value){ $arrSort[$key][$uniqid] = $value; } } if($sort['direction']){ array_multisort($arrSort[$sort['field']], constant($sort['direction']), $data); } return $data; }