Accessing a variable that starts with an integer within results generated by json_decode
I feel really stupid right now. The following code should output 'If you can get this text to print, you're neat!', but it doesn't. Any ideas?
<?php
$a = (Array) json_decode("{\"406\":开发者_StackOverflow\"If you can get this text to print, you're neat!\"}");
// dump($a);
echo $a[406]."\n";
echo $a["406"]."\n";
echo $a['"406"']."\n";
echo $a["'406'"]."\n";
$a = Array(406=>'Sanity check: this works, why don\'t any of the previous accessors work?');
// dump($a);
echo $a[406]."\n";
function dump($a) {
foreach ($a as $k => $v) {
echo "$k=>$v\n";
}
}
?>
Your original example was returning an object because of a second optional parameter for return type that has the default of FALSE
, or to return an object. This is how you would treat it...
$a = json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}", FALSE);
echo $a->{"406"}; // If you can get this text to print, you're neat!
A little tweaking and you can create an array instead...
$a = json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}", TRUE);
echo $a["406"]; // If you can get this text to print, you're neat!
... and you can reference $a
as an array like you were originally attempting. Notice what was happening when you were trying to type cast the original object. Here's a var_dump of the original array you created followed by the resulting array from using the optional TRUE
parameter.
array(1) { ["406"]=> string(47) "If you can get this text to print, you're neat!" }
array(1) { [406]=> string(47) "If you can get this text to print, you're neat!" }
Do you see how it was adding the quotes to your array key when you were type casting it from an object? This is why you weren't able to return the correct value; because the array key had changed.
This did work for me:
$a = json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}", true);
I added another parameter to json_deocde.
Your using a json object, not an array.
json object:
{"keyname":"keyvalue"}
Json array:
["value1","value2"]
Since it is an object, you can access it as such.
$json=json_decode("{'keyname':'keyvalue'}";
$keyname=$json->keyname;
精彩评论