StackG
StackG

Reputation: 2858

PHP json_decode to associative array

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 );

Upvotes: 1

Views: 1466

Answers (1)

steven
steven

Reputation: 4875

I don't know if this is the right place here to discuss php's default parameters but if i like to change it i would do it like this:

function my_json_decode($json, $assoc=true, $depth=512, $options=0) {
    return json_decode($json, $assoc, $depth, $options);
} 

I hope i understood your question correctly. Please correct me if i don't. I am not shure if the majority of use-cases need the assoc-argument set to true. But I fear there will be a lot of trouble if they change it to true right now, because a lot of code needs to be rewritten.

Upvotes: 2

Related Questions