首页 > 解决方案 > 为什么这个 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>";
        }
    }    
}

?>

标签: phpjson

解决方案


您没有array_key_exists正确使用该特定情况(您在其他地方正确使用它)。正确的用法是

array_key_exists ( mixed $key , array $array )

因此,对于您要检查的内容,您应该使用

array_key_exists($a, $json_a["Guids"][$g]["Broke"][$b]);

推荐阅读