检查数组

时间:2016-05-03 18:10:12

标签: php arrays

修改

if(array_key_exists($errcode, $Errors)){
    $Data['status'] = -1;
    $Data['err'] = array(
        "err_code" => $errcode,
        "err_str" => $Errors[$errcode]
    );
}

我有一个艰难的时间来确定数组中是否存在某个键,我尝试使用 array_key_exists 方法,但没有运气!我还尝试过 empty($ array [$ key]),它似乎返回相同的通用错误而不是特定的错误。

调用err(null,3)将输出:

{
    "status": -1,
    "err": {
        "err_code": null,
        "err_str": "Generic error"
    }
}

我尝试使用array_key_exists方法返回bool但它似乎不起作用,为什么会这样?

My site should output error 5: Invalid

//Errors ENUM
$Errors = array(
    0 => "Cannot parse <GameID>",
    1 => "Invalid steam session",
    2 => "Invalid <GameID>, non-numeric",
    3 => "SQL Connection refused",
    4 => "SQL Query error",
    5 => "invalid <GameID>"
);

function err($status, $errcode){
    if(isset($errcode)){
        if($Errors[$errcode] != null){
            $Data['status'] = -1;
            $Data['err'] = array(
                "err_code" => $errcode,
                "err_str" => $Errors[$errcode]
            );
        } else {
            $Data['status'] = -1;
            $Data['err'] = array(
                "err_code" => null,
                "err_str" => "Generic error"
            );
        } 
    } else {
        $Data['status'] = $status;
        $Data['err'] = array(
            "err_code" => null,
            "err_str" => null
        );
    }
    echo(json_encode($Data, 128 | 32));
}

1 个答案:

答案 0 :(得分:0)

err函数没有看到全局$ Errors变量。在Err函数中声明Errors变量为global

function err($status, $errcode){
    global $Errors;
    if(isset($errcode)){
        if($Errors[$errcode] != null){
            $Data['status'] = -1;
            $Data['err'] = array(
                "err_code" => $errcode,
                "err_str" => $Errors[$errcode]
            );
        } else {
            $Data['status'] = -1;
            $Data['err'] = array(
                "err_code" => null,
                "err_str" => "Generic error"
            );
        } 
    } else {
        $Data['status'] = $status;
        $Data['err'] = array(
           "err_code" => null,
           "err_str" => null
        );
   }
   echo(json_encode($Data, 128 | 32));
}