Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode sparse json object to php array

Tags:

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

like image 255
Isaac Sutherland Avatar asked Mar 20 '10 20:03

Isaac Sutherland


People also ask

How can access JSON decoded data in PHP?

PHP - Accessing the Decoded Values$obj = json_decode($jsonobj);

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

What json_decode () function will return?

Syntax. The json_decode() function can take a JSON encoded string and convert into a PHP variable. The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively.

How do I decode a JSON file?

You just have to use json_decode() function to convert JSON objects to the appropriate PHP data type. Example: By default the json_decode() function returns an object. You can optionally specify a second parameter that accepts a boolean value. When it is set as “true”, JSON objects are decoded into associative arrays.


1 Answers

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.

like image 101
Chris Avatar answered Oct 22 '22 20:10

Chris