php - 为什么这个 json 值不是 PHP 数组键?
问题描述
解析下面的json时,PHP语句:
if (array_key_exists($json_a["Guids"][$g]["Broke"][$b][$a])) {
尽管“Demo”是一个“键”,但从不计算为真,如 print_r 语句所示。
我在测试json中是否确实存在“Demo”或“Live”时做错了什么?(对于任何给定的记录,一个或另一个或两者都可能存在)
谢谢你。
杰森:
{
"MinimumVersion": "20191101",
"Guids": {
"0ebe7e53-12fc-4f8f-a873-4872fe30bbee": {
"Broke": {
"Yes": {
"Demo" : { "Expires" : "" },
"Live" : { "Expires" : "" }
},
"No": {
"Demo" : { "Expires" : "20191104" },
"Live" : { "Expries" : "" }
}
},
"Message": "You need to upgrade to the latest version."
}
}
}
PHP:
<?php
$string = file_get_contents("json.txt");
$json_a = json_decode($string,true);
$g = "0ebe7e53-12fc-4f8f-a873-4872fe30bbee";
$b = "No";
$a = "Demo";
echo "G: \"" . $g . "\"<br>";
echo "B: \"" . $b . "\"<br>";
echo "A: \"" . $a . "\"<br>";
if (is_array($json_a["Guids"][$g]["Broke"][$b][$a])) {
#This next line prints Array ([0] => Expires )
print_r(array_keys($json_a["Guids"][$g]["Broke"][$b][$a]));
} else {
echo "Test: false";
}
if (array_key_exists($g,$json_a["Guids"])) {
echo ("true1");
if (array_key_exists($b,$json_a["Guids"][$g]["Broke"])) {
echo ("true2");
if (array_key_exists($json_a["Guids"][$g]["Broke"][$b][$a])) {
#this never evaluates to true. Why? "Demo" is a "key" as shown from the print_r results statement above.
echo "Value:\"" . $json_a["Guids"][$g]["Broke"][$b][$a] . "\"<br>";
}
}
}
?>
解决方案
您没有array_key_exists
正确使用该特定情况(您在其他地方正确使用它)。正确的用法是
array_key_exists ( mixed $key , array $array )
因此,对于您要检查的内容,您应该使用
array_key_exists($a, $json_a["Guids"][$g]["Broke"][$b]);
推荐阅读
- python-3.x - Python3 x Socket - ICMP Echo 请求 - 为什么我的套接字挂在 recv 上?
- sonata-admin - Sonata-Project 的 Google Authenticator:来自 Application\Sonata\UserBundle\Entity\User 的未定义方法“getTwoStepVerificationCode”
- javascript - BootstrapToggle switch 有条件地切换状态
- elasticsearch - Elasticsearch 索引不尊重模板和映射
- amazon-web-services - 在来自胶水爬虫的 ETL 之后流水线化 Athena 查询
- regex - 如何在VS2017中使用正则表达式从响应头中提取requesttoken?
- jdbc - apache Beam中普通JDBC和JDBCIO连接器的区别?
- python - 使用 Python 请求库时出现错误 10060
- maven - 用于 Maven 部署插件的多模块项目中 POM 文件的位置
- multithreading - 上下文切换不准确到 UNIX 中的主线程