So, I haven't seen any other answers touch upon this, but @xdazz came close.
Let's start our environment, $obj
equals the object notation of a decoded string:
php > $obj = json_decode('{"1":1,"2":2}');
php > print_r($obj);
stdClass Object
(
[1] => 1
[2] => 2
)
php > var_dump( $obj );
object(stdClass)#1 (2) {
["1"]=>
int(1)
["2"]=>
int(2)
}
If you want to access the strings, we know the following will fail:
php > echo $obj->1;
Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `'{'' or `'$'' in php shell code on line 1
Accessing the object variables
You can access it like so:
php > echo $obj->{1};
1
Which is the same as saying:
php > echo $obj->{'1'};
1
Accessing the array variables
The issue with arrays is that the following return blank, which is the issue with typecasting.
php > echo $obj[1];
php >
If you typecast it back, the object is once again accessible:
php > $obj = (object) $obj;
php > echo $obj->{1};
1
Here is a function which will automate the above for you:
function array_key($array, $key){
$obj = (object) $array;
return $obj->{$key};
}
Example usage:
php > $obj = (array) $obj;
php > echo array_key($obj, 1);
1
php > echo array_key($obj, 2);
2