0

From a json decode, I have an std that has a key called

@MyKey

Note the @ symbol prefix. I'm not sure how to access it because doing:

$item['@MyKey']

Results in

 Cannot use object of type stdClass as array

And doing

$item->@MyKey

Results in

 syntax error, unexpected '@', expecting T_STRING or T_VARIABLE
K2xL
  • 9,730
  • 18
  • 64
  • 101

3 Answers3

3

Just figured it out:

$item->{'@MyKey'}
K2xL
  • 9,730
  • 18
  • 64
  • 101
  • Note that you can also decode your json as plain arrays, by passing `true` as second parameter: `json_decode(..., true)`. – Arnaud Le Blanc May 23 '13 at 13:57
  • Make sure to mark this as the correct answer when you can to help future visitors. Perhaps you could also provide some reference or documentation to explain your solution? – Kermit May 23 '13 at 13:57
  • @FreshPrinceOfSO I can't accept my own answer for another two days. – K2xL May 23 '13 at 14:36
0

You can access them using the curly syntax. Example:

$json = '{ "@test"  : { "@foo" : "bar" }}';

$obj = json_decode($json);

echo $obj->{'@test'}->{'@foo'};
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

you can cast the item to an array and use array accessors as normal

$itemArray = (array)$item; 

echo $itemArray["@MyKey"];
Orangepill
  • 24,500
  • 3
  • 42
  • 63