[PHP/JSON] Getting an object key

{   "1": ...,   "2": ...,   "user-data": ...,}

When working with JSON data in PHP, you might encounter keys that are not valid PHP identifiers due to special characters, while PHP identifiers are supposed to start with an alpha and not contain a hyphon (e.g $object->1 or $object->user-data).

Here are some approaches to handle such cases:

Dynamic Property Access:

To access a JSON key with a hyphen or other non-standard characters, you can use dynamic property access with curly braces ({}).

$json = file_get_contents('data.json');$object = json_decode($json);print_r( $object->{'user-data'} );

Casting to an Array:

If you prefer to work with arrays instead of objects, you can cast the decoded JSON to an associative array.

$array = (array)$object;print_r( $array[1] );

or

// It's also possible to cast it to an array using json_decode second argument$array = json_decode($json, true);

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *