1

Possible Duplicate:
How do I access this object property?

The data returned in a request is (JSON):

stdClass Object
(
[USD] => stdClass Object
    (
        [7d] => 23.3414

I'm calling:

json_decode(...);

And trying to access it via:

echo $json->USD->7d;

But that fails, because the variable name cannot start with an integer. Is there any syntax in PHP for accessing this?

Otherwise I would fix this by doing:

$set = (array) $json->USD;
echo $set['7d'];
Community
  • 1
  • 1
mr-sk
  • 13,174
  • 11
  • 66
  • 101

3 Answers3

8

This is working:

$name = '7bar';
$o->$name = 'foo';
echo $o->{'7bar'};

As you see in the example there are two different ways to access variables with uncommon names.

flori
  • 14,339
  • 4
  • 56
  • 63
5
json_decode($var, true);

sets object to an assoc array, not your answer but saves typecast call.

Cups
  • 6,901
  • 3
  • 26
  • 30
  • +1 cool, I'm'a use this, thanks. But I'm going accept "flori"s answers as the *correct* one. – mr-sk Jun 11 '11 at 21:13
0

Why not change the variable name from 7d to something like d7? Is there a reason for the 7d reference?