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.)
PHP - Accessing the Decoded Values$obj = json_decode($jsonobj);
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With