0

I am parsing large json structures using json_decode() returning an object $obj. Within the object, it is necessary to replace some key/value pairs:

unset($obj->$oldkey);
$obj->$newkey = $newvalue;

Appearently, the new key/value pair will be appended at the end of object, while the old key/value pair is deleted from an abitrary position. How can I preserve the old order, i.e. a replacement at the same position?

EDIT: A possible solution may be to unset all keys and set all key/value pais new, but isn't there an easier way?

Stefan
  • 137
  • 13
  • 1
    How come the order matters? It's very rare that it does, particularly as you've mentioned JSON (which is also not order sensitive). – Luke Briggs Nov 27 '16 at 06:54
  • The order matters, since json is used to define the order. json_decode keeps the order, this feature is simply used to transfer the order to the "php world". – Stefan Nov 27 '16 at 06:58
  • There's no guarantee that going to/ from JSON will actually preserve the order at all times. You should use `[]` instead to declare the order yourself, i.e. ['oldkey','someOtherKey',..] etc. – Luke Briggs Nov 27 '16 at 07:02
  • You may be right that an explicit definition of the order may be the best way, but I do not have control over the json structures. I don't know the implementation of json_decode, but I can't see any reason for a disordering in json_decode. – Stefan Nov 27 '16 at 07:05
  • It's PHP. That's [reason enough](https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/) ;) – Luke Briggs Nov 27 '16 at 07:06
  • If you are willing to `json_decode` as an array (add an extra `true` argument to the function call) instead of an object, you could try something like [this](http://stackoverflow.com/questions/3353745/how-to-insert-element-into-arrays-at-specific-position). – segFault Nov 27 '16 at 07:45

0 Answers0