Jason94
Jason94

Reputation: 13620

cannot use object of type stdClass as array when trying to modify a array

I've just read a simple array from my db that was json_encoded, so i decoded it and tried to change a value at index 0, but i get the following error

cannot use object of type stdClass as array when trying to modify a array

any help?

Upvotes: 0

Views: 1398

Answers (2)

Andy
Andy

Reputation: 17791

A JSON-encoded entity can be an object or an array - it appears that in your example it's an object (of type stdClass). You can either reference it as an object

$jsonProperty = $decoded->property;

save the original JSON object as an array

$encodedJson = json_encode((array) $object);

or force decoding as an associative array

$decodedJson = json_decode($json, true);

Personally I'd use the first option and refer to a JSON object with PHP's object access notation for clarity.

Upvotes: 2

mishu
mishu

Reputation: 5397

by default json strings are decoded as objects and not arrays. so you must use json_decode's second parameter. so your call should be like this:

$array = json_decode($string, true);

Upvotes: 3

Related Questions