我无法使用array_key_exist获取指定的密钥以进行JSON响应

时间:2019-06-18 07:24:26

标签: php arrays json codeigniter

$status_key ="status"

$response = {"error":false,"data":{"id":16420728,"order_id":"5000","mobile_no":"9995088810","amount":20,"balance":46.89,"status":"failure","tnx_id":"","response":"Transaction Failed"}}"


$result = json_decode($response);

此打印:

{ 
    ["error"]=> bool(false) 
    ["data"]=> object(stdClass)#24 (8) { 
        ["id"]=> int(16420728) 
        ["order_id"]=> string(4) "5000" 
        ["mobile_no"]=> string(10) "9995088810" 
        ["amount"]=> int(20) 
        ["balance"]=> float(46.89) 
        ["status"]=> string(7) "failure" 
        ["tnx_id"]=> string(0) "" 
        ["response"]=> string(18) "Transaction Failed" 
    }
}

现在我正在检查指定的密钥

var_dump(array_key_exist(status_key,result));

当我执行var_dump()此功能时,它将返回"bool(false)"

1 个答案:

答案 0 :(得分:2)

您有很多语法错误,还需要像下面这样修改代码:

var_dump(array_key_exists($status_key,$result->data));
//- --------------------^-^-----------^-------^--^-- missing those

输出:-https://3v4l.org/uWB7s

为寻求更好的搜索方法, 寻求帮助:Check if specific array key exists in multidimensional array - PHP

$result = json_decode($response, true);

var_dump(findKey($result, $status_key));

function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key == $keySearch) {
            return true;
        } elseif (is_array($item) && findKey($item, $keySearch)) {
            return true;
        }
    }
    return false;
}

输出:-{https://3v4l.org/KaX9F