If you use objects as dynamic dictionaries (and I suppose you do), I think you want to use ArrayObject .
It appears in the JSON dictionary even when it is empty. Great if you need to distinguish between lists (arrays) and dictionaries (associative arrays):
$complex = array('list' => array(), 'dict' => new ArrayObject()); print json_encode($complex);
You can also easily manipulate it (as it would with an associative array), and it will display correctly in the dictionary:
$complex['dict']['a'] = 123; print json_encode($complex); // -> {"list":[],"dict":{"a":123}} unset($complex['dict']['a']); print json_encode($complex); // -> {"list":[],"dict":{}}
If you want this to be 100% compatible in both directions , you can also wrap json_decode so that it returns ArrayObjects instead of stdClass (you will need to go through the result tree and recursively replace all objects, which is a pretty simple task).
Gotchas . Only the one I found so far: is_array(new ArrayObject()) evaluates to false . You may need to find and replace the is_array occurrences in your code (use (($foo instanceof ArrayObject) || is_array($foo)) ).
wrygiel May 21 '13 at 8:17 2013-05-21 08:17
source share