简体   繁体   English

为什么这个 json 值不是 PHP 数组键?

[英]Why is this json value not a PHP array key?

When parsing the json below, the PHP statement:在解析下面的json时,PHP语句:

if (array_key_exists($json_a["Guids"][$g]["Broke"][$b][$a])) {

never evaluates to true despite that "Demo" is a "key" as shown from the print_r statement.尽管“Demo”是一个“键”,但从不计算为真,如 print_r 语句所示。

What am I doing wrong on how I'm testing to see if "Demo" or "Live" actually exists in the json?我在测试 json 中是否确实存在“演示”或“现场”时做错了什么? (one or the other or both may be there for any given record) (对于任何给定的记录,一个或另一个或两者都可能存在)

Thank you.谢谢你。

Json: Json:

{
  "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:

<?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>";
        }
    }    
}

?>

You're not using array_key_exists properly for that particular case (you use it correctly elsewhere).您没有针对该特定情况正确使用array_key_exists (您在其他地方正确使用它)。 The correct usage is正确的用法是

array_key_exists ( mixed $key , array $array )

so for what you want to check, you should use因此,对于您要检查的内容,您应该使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM