如何知道 Json 字符串中是否存在密钥 [英] how to know whether key exists in Json string
问题描述
可能的重复:
如何检查数组元素是否存在?
如果我错了,请道歉,我是 PHP 新手,在使用 PHP 中的 json_decode
函数解码后,有没有办法找出 Json
字符串中是否存在密钥.
apologize if i am wrong,I am new to PHP, Is there any way to find out whether key exists in Json
string after decoding using json_decode
function in PHP.
$json = {"user_id":"51","password":"abc123fo"};
简要:
$json = {"password":"abc123fo"};
$mydata = json_decode($json,true);
user_id = $mydata['user_id'];
如果json字符串不包含user_id,它会抛出类似Undefined index user_id
的异常,那么有什么方法可以检查Json字符串中是否存在key,请帮帮我,我正在使用PHP 5.3 和 Codeigniter 2.1 MVC
提前致谢
If json string doesn't consist of user_id,it throws an exception like Undefined index user_id
,so is there any way to check whether key exists in Json string,Please help me,I am using PHP 5.3 and Codeigniter 2.1 MVC
Thanks in advance
推荐答案
如果你还想检查值是否不是 null
你可以使用 isset
IF you want to also check if the value is not null
you can use isset
if( isset( $mydata['user_id'] ) ){
// do something
}
即array_key_exists
和 isset
的区别在于与
i.e. the difference between array_key_exists
and isset
is that with
$json = {"user_id": null}
array_key_exists
将返回 true
而 isset
将返回 false
array_key_exists
will return true
whereas isset
will return false
这篇关于如何知道 Json 字符串中是否存在密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!