0

I am using PHP, but question is not entirely PHP specific.

I've got a need to serialize object, current I am using JSON format and this could be example of serialized object: {"22":{"val":"e","gIds":["48"]},"23":{"val":"e","gIds":["235"]}}

Given this format I can simply use PHP's : $array = json_decode($string, true), then I can use either isset($array[22]) or array_key_exists(22, $array) for quick lookups, which I think would be equivalent to hashmap / dictionary in different languages.

Unfortunately the JSON format by default doesn't keep the order of properties within the object (https://stackoverflow.com/a/7214312/2263395). The order might be consistent in the same version of PHP, but it's not guaranteed behavior according to JSON standard.

I could make it a list of nested objects: [{"22":{"val":"e","gIds":["48"]}},{"23":{"val":"e","gIds":["235"]}}] or even move the id inside: [{"id": "22","val":"e","gIds":["48"]},{"id": "23","val":"e","gIds":["235"]}] That way I can preserve order, however each I can no longer use the quick lookup functions like: isset or array_key_exists before I create a hashmap. For JSONs having thousands of items, I would have to iterate that many times in order to prepare a hashmap, so I can use the quick lookup function.

Can I have the both order and speed, is there any format that could do that?

Speaking of PHP options is there any performant competitor?

Tom Raganowicz
  • 2,169
  • 5
  • 27
  • 41
  • The order on the “outer” level, ids 22 and 23, is the only one that is important? Maybe add a bit of redundancy then? Supply an array with just those ids in addition to your data that you already have? `[22, 23]` preserves the order, _and_ can be used for quick lookups (`in_array`). And you can then use these values to access the rest of the data under that key in your original object. – 04FS Jun 04 '19 at 12:37
  • I need to keep the order for the sake of calculating repeatable hash each time, so the redundancy doesn't really solve that, since there is still the same chance that dictionary elements order will be different, therefore hash itself will be completely different. Now I've realized that even if I keep the order on the "outer" level in tact, still my my inner object with `val`, `gIds` fields shares the same issue. There is no guarantee their order will be preserved. Either I find consistent way of storing object/dictionaries or I need to rework whole concept. – Tom Raganowicz Jun 04 '19 at 15:34

0 Answers0