Decode sparse json array to php array

Posted by Isaac Sutherland on Stack Overflow See other posts from Stack Overflow or by Isaac Sutherland
Published on 2010-03-20T20:48:45Z Indexed on 2010/03/20 20:51 UTC
Read the original article Hit count: 539

Filed under:
|
|
|
|

I can create a sparse php array (or map) using the command:

$myarray = array(10=>'hi','test20'=>'howdy');

I want to serialize/deserialize this as JSON. I can serialize it using the command:

$json = json_encode($myarray);

which results in the string {"10":"hi","test20":"howdy"}. However, when I deserialize this and cast it to an array using the command:

$mynewarray = (array)json_decode($json);

I seem to lose any mappings with keys which were not valid php identifiers. That is, mynewarray has mapping 'test20'=>'howdy', but not 10=>'hi' nor '10'=>'hi'.

Is there a way to preserve the numerical keys in a php map when converting to and back from json using the standard json_encode / json_decode functions?

© Stack Overflow or respective owner

Related posts about php

Related posts about JSON