【问题标题】:Checking if key exists in array [duplicate]检查数组中是否存在键[重复]
【发布时间】:2016-08-28 22:14:47
【问题描述】:

编辑:

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 方法,但它似乎不起作用,这是为什么呢?

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));
}

【问题讨论】:

  • 告诉我们你是如何尝试使用array_key_exists函数的。
  • array_key_exists() 返回 BOOL?这怎么行不通? 正是它应该返回的内容。
  • 问题是变量作用域:$Errors 没有在err() 函数中定义。

标签: php arrays


【解决方案1】:

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));
}

【讨论】:

  • 为什么 OP 应该尝试这个? 好的答案将始终解释所做的事情以及为什么以这种方式完成,不仅是为了 OP,而且是为了未来的 SO 访问者。在 Stack Overlfow 上,仅代码答案尤其不可接受。
  • 这会起作用,但我想知道为什么解决方案不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-30
  • 2021-08-06
  • 2011-11-14
  • 2011-12-14
  • 2018-11-15
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多