php 如何知道 Json 字符串中是否存在密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10176293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:34:46  来源:igfitidea点击:

how to know whether key exists in Json string

phpcodeigniter

提问by Nishanth

Possible Duplicate:
How to check if an array element exists?

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

apologize if i am wrong,I am new to PHP, Is there any way to find out whether key exists in Jsonstring after decoding using json_decodefunction in PHP.

抱歉,如果我错了,我是 PHP 新手,在Json使用json_decodePHP 中的函数解码后,有没有办法找出字符串中是否存在键。

$json = {"user_id":"51","password":"abc123fo"};

Brief:

简短的:

$json = {"password":"abc123fo"};
$mydata = json_decode($json,true);
user_id = $mydata['user_id'];

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 MVCThanks in advance

如果json字符串不包含user_id,它会抛出一个异常Undefined index user_id,那么有没有办法检查Json字符串中是否存在键,请帮帮我,我正在使用PHP 5.3 and Codeigniter 2.1 MVC提前谢谢

回答by scibuff

IF you want to also check if the value is not nullyou can use isset

如果您还想检查该值是否不是null您可以使用isset

if( isset( $mydata['user_id'] ) ){
   // do something
}

i.e. the difference between array_key_existsand issetis that with

即之间的差array_key_exists,并isset是与

$json = {"user_id": null}

array_key_existswill return truewhereas issetwill return false

array_key_exists会回来trueisset会回来false

回答by Jordan

You can try array_key_exists.

你可以试试array_key_exists

It returns a boolean value, so you could search for it something like:

它返回一个布尔值,因此您可以搜索它,例如:

if(array_key_exists('user_id', $mydata)) {
    //key exists, do stuff
}