Decode sparse json object to php array

Isaac Sutherland picture Isaac Sutherland · Mar 20, 2010 · Viewed 39.7k times · Source

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?

(I am using PHP Version 5.2.10-2ubuntu6.4.)

Answer

Chris picture Chris · Mar 20, 2010

json_decode returns an object of type stdClass by default. You access members as properties (i.e., $result->test20). 10 isn't a valid name for a property, which is why you're losing it.

Instead of casting to an array, you can pass true as a second argument to json_decode to make it return an associative array itself:

$mynewarray = json_decode($json, true);

If you do that, $mynewarray[10] will work fine.