如何知道密钥是否存在于Json字符串中 [英] how to know whether key exists in Json string

查看:32
本文介绍了如何知道密钥是否存在于Json字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何检查数组元素是否存在?

道歉,如果我错了,我是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字符串中是否存在密钥,请帮助我,我正在使用 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 之间的区别在于

$json = {"user_id": null}

array_key_exists 将返回 true ,而 isset 将返回 false

这篇关于如何知道密钥是否存在于Json字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆