Converting arrays to JSON and back again
Posted on 2009-04-02
I'm doing some experimentation with storing values in JSON, specifically arrays.
For simple, for one dimensional arrays this is not too difficult:
$json = json_encode($array) converts the array to JSON and then to get the array back again you do:
$object = json_decode($json); $array = get_object_vars($object);
However, this becomes more complicated with multidimensional arrays. Encoding is not a problem, but the decode process does not work the same. json_decode creates a multidimensional object (is there such a thing as a multidimensional object?). At any rate, get_object_values leaves objects as objects in the array and you might end up with something like:
Array ( [what] => is [this] => was [number] => 8 [array] => stdClass Object ( [second] => level ) )
My question is: Is there a way to deal with this easily? Or will I need to build recursive function myself that reads through all the values of the object to convert them to array key=>value pairs, testing for objects as it goes and then calling itself to convert embedded objects?