I have just been bashing my head against a brick wall for several hours trying to use the json_decode()
function in PHP. The same problem has appeared on Stack Overflow many times, for example here and here.
The solution was that, as stated in the docs, if you want to get an associative array from a JSON object, you need to include a second, optional true
parameter in your function call, like this:
$assoc_array = json_decode($the_JSON,true);
On the other hand, leaving this parameter out returns an object instead:
$php_objest = json_decode($the_JSON);
This is most annoying for me because it's a problem I've solved before some time ago, but forgot.
Do people agree that having this defaulting to true
rather than false
reflects the majority of use-cases?
Edit: As requested below, the use-case that caused this error (similar to what I've done in the past) was trying to decode a JSON object, add/re-arrange some values, and then re-encode. A code example is:
$the_hardcoded_json_string = "{\"a\":60,\"vi\":0,\"is\":0}";
$the_associative_array = json_decode( $the_hardcoded_json_string, true );
$the_associative_array["c"] = 758;
$the_new_json_string = json_encode( $the_associative_array );