I'm trying to get some info out of a decoded JSon string into an array.
I've this code:
$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];
The problem is, I need to get the value for "status" of "iklive.com" but when I do echo $json_a[$full_domain][status]; it does not work, but if I do it manually like echo $json_a['iklive.com'][status]; (with the quotes there) it works.
I've tried to add the quotes to the variable but without success, how can I do this?
Thanks Everyone!
Thanks to Pekka and jeromegamez I noticed a error in the HTML part of this "problem", the $tlds variable was "com" instead of ".com" -- Sorry by wasting your time with this. I do feel bad now.
Anyway, thanks to jeromegamez and Marc B I discovered that unless status was a constant I need to quote it ;) You can check jeromegamez answer to a detailed explanation of the problem and proper debug.
Sorry.
1 Answer 1
This works for me:
<?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";
}
What I did:
- Changed
json_a[$full_domain][status]tojson_a[$full_domain]['status']- the missing quotes aroundstatusdon't break your script, but raise aNotice: Use of undefined constant status - assumed 'status' - Added a check if the decoded JSON is actually an array
- Added a check whether the key
$full_domainis set in$json_a
2 Comments
['status'] quoted! Thanks! ;)
$full_domainis?$full_domain='iklive.com'?$full_domainhas that value? Then there shouldn't be a problem. Are you keeping in mind that array indexes are case sensitive?statushasn't been quoted. Unless you've got astatusconstant define()'d, a PHP install in strict mode should gripe about both versions.