2011-11-03 67 views
1

我试图从解码的JSon字符串中获取一些信息到数组中。PHP和JSON - 解码阵列问题?

我有这样的代码:

$json_d='{ // This is just an example, I normally get this from a request... 
      "iklive.com":{"status":"regthroughothers","classkey":"domcno"} 
}'; 

$json_a=json_decode($json_d,true); 
$full_domain = $domain.$tlds; // $domain = 'iklive' ; $tlds = '.com' 

echo $json_a[$full_domain][status]; 

的问题是,我需要获得的“iklive.com”但是当我做echo $json_a[$full_domain][status];这是行不通的“状态”的值,但如果我手动操作,如echo $json_a['iklive.com'][status];(带引号)。

我试图将变量添加到变量但没有成功,我该怎么做?

谢谢大家!


感谢佩卡和jeromegamez我注意到,在这个“问题”的HTML部分错误,$tlds变量是不是“COM”,“.COM” - 用这浪费你的时间很抱歉。我现在感觉很糟糕。

无论如何,由于jeromegamez和马克B我发现,除非status是一个常数,我需要引用它;)你可以检查jeromegamez答案的问题和适当的调试的详细说明。

对不起。

+0

而'$ full_domain'的值是? – Brad

+1

你确定'$ full_domain ='iklive.com'吗? – ComFreek

+0

你是100%正面'$ full_domain'有那个值?那么就不应该有问题。你是否记住数组索引是区分大小写的? –

回答

2

这个工作对我来说:

<?php 
$json_d='{ "iklive.com":{"status":"regthroughothers","classkey":"domcno"} }'; 
$json_a = json_decode($json_d, true); 

if (!is_array($json_a)) { 
    echo "\$json_d is not a valid JSON array\n"; 
} 

$domain = "iklive"; 
$tld = ".com"; 
$full_domain = $domain . $tld; 

if (!isset($json_a[$full_domain])) { 
    echo "{$full_domain} is not set in \$json_a\n"; 
} else { 
    echo $json_a[$full_domain]['status']."\n"; 
} 

我所做的:

  • 改变json_a[$full_domain][status]json_a[$full_domain]['status'] - 围绕status缺失报价不破你的脚本,但提出一个Notice: Use of undefined constant status - assumed 'status'
  • 增加了一个检查,如果解码的JSON实际上是一个数组
  • 增加了一个检查密钥$full_domain设置在$json_a
+0

你也可以插入'json_last_error()';) – ComFreek

+0

...或单元测试:) – jeromegamez

+0

你是最棒的!通过问题发现,在发布$ domain和$ tld变量的HTML文件中犯了一个愚蠢的错误。对不起,浪费你的时间伙计。无论如何,我注意到我还没有使用'['status']'引用!谢谢! ;) – TCB13