[英]Why is this json value not a PHP array key?
在解析下面的json時,PHP語句:
if (array_key_exists($json_a["Guids"][$g]["Broke"][$b][$a])) {
盡管“Demo”是一個“鍵”,但從不計算為真,如 print_r 語句所示。
我在測試 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
$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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.