Home  >  Article  >  php教程  >  通用返回特定格式的请求状态函数

通用返回特定格式的请求状态函数

WBOY
WBOYOriginal
2016-06-07 11:36:48863browse

返回状态码,消息,数据等内容特定格式的内容,它可以传1到5个参数,分别代表不同意义.
通用返回特定格式的请求状态函数$code = 'REGISTAR_FAILED';
$info = '-123';
$record = array(array('aaa','bbb'));
$count = 2;
$infovalue =  array(123456789,  '。当前时间:'.date('Y-m-d H:i:s'));

print_r(back($code, $info, $record, $count, $infovalue));
print_r(back($code, $info, $record, $count));
print_r(back($code, $info, $record, $infovalue));//四个参数时, 第四个数组,就代表$infovalue
print_r(back(1,     $info, $record));//三个参数时,第一个为1(成功),第三个表示$record
print_r(back($code, $info, $infovalue));//三个参数时,不为1时(失败),第三个表示$infovalue
print_r(back($code, $info));
print_r(back($code));



/**
 * 返回状态数据
 * @param string $code 状态符
 * @param string $info  消息内容/状态码
 * @param array $record 返回数据/变量参数
 * @param number $count 记录条数
 * @return array
 */
function back($code, $info=null, $record=null, $count=null, $infovalue=array()){
    
    $numargs = func_num_args();
    switch($numargs){
        case 2 : if(is_array($info)){$record = $info; $info = null;}
            break;
        case 3 : if($code != 1 && !empty($record)){$infovalue = $record; $record = null;}
            break;
        case 4 : if(is_array($count)){$infovalue = $count; $count = null;}
    }

    $mincode = '';
    //消息内容为数字
    if(is_numeric($info)){
        $mincode = '('.$info.')'; $info = null;
    }
    
    if(empty($info)){
        //错误消息配置
        $STATUS_CODE = array('REGISTAR_FAILED' => '手机号码{0}不正确{1}' );
        $info = isset($STATUS_CODE[$code])? $STATUS_CODE[$code] : ($code == 1? 'success' : '未知错误');
    }
    
    $pattern  = '/\{(\w*)\}/';
    if(!empty($infovalue) && preg_match($pattern, $info)){
        $str = '';
        $str .= preg_replace_callback($pattern, function($matches){
            return '{$infovalue['.$matches[1].']}';
        }, $info);
        eval('$info="'.$str.'";');
    }

    $return = array('status'=>$code, 'info'=>$info.$mincode, 'count'=>$count, 'data'=>$record);
    if($count == null) unset($return['count']);
    if($record == null) unset($return['data']);
    return $return;
}

AD:真正免费,域名+虚机+企业邮箱=0元

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Gms管理系统v1.1.1Next article:读取目录(精简)