Reputation: 451
i need to store php variables into files so i decide to serialize or jsonize (maybe jsonify XD) them.
For portability purpose i prefer json solution...
During test i notice associative array are json-decoded as object and i cant use it as associative array but i have to use as object.
Non-associative array are json-decoded correctly as non-associative array..
am i doing something wrong?
or just this is a normal behavior of php json functions
here the example code
$test = array("test1" => 1, "test2" => 2);
$json = json_decode(json_encode($test));
$serialize = unserialize(serialize($test));
//output -> stdClass::__set_state(array( 'test1' => 1, 'test2' => 2, ))
// cant access to $json["test1"] as in $test but $json->test why?????
var_export($json);
//ouptut -> array ( 'test1' => 1, 'test2' => 2, )
//here i can $serialize["test1"]
var_export($serialize);
Upvotes: 2
Views: 2711
Reputation: 451
yes i already use it...
if i use json_decode($test, true)
works on associative array but wont work for object cause original object will be decoded as array...
So the problem is i must have the decoded variables as the original variables (for both case).
I encode my variables then store in a file then decode and i must access them in the same way i access the original, so if the original was associative array i must access it as associative array x["field"]
, if the original variables was a object i have to access as object x->field
.
Serialize do the job, json no, thats my concern... maybe json is not thought for that purpose?
Upvotes: 0
Reputation: 1540
You can give set a second Parameter. When TRUE, returned objects will be converted into associative arrays. http://php.net/manual/en/function.json-decode.php
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
output:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Upvotes: 0