2

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);
1
  • 3
    Just use json_decode(json_encode($test), true);, you'll get an array instead of an object. Commented Jul 2, 2015 at 15:48

3 Answers 3

1

have you tried json_decode($test, true) ?

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

and what about nested?
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.