php - JSON object conversion question -


I am converting from object and object to JSON into an array. I do not expect this, can you explain me?

  $ json = '{"0": "a"}'; $ Obj = json_decode ($ json); $ A = (array) $ obj; Print_r (single $); Echo ("a0:" a ["0"] "& lt; br & gt;" $); $ B = array ("0" =>, "b"); Print_r ($ B); Echo (. "B0:" $ b ["0"] "& lt; br & gt;".); Here is the output:  
  array ([0] => a) a0: array ([0] = & gt; b) B. 0: b  

I will be a0: a at the end of the first line.

Edit: After reading the answer, I increased the code, which makes the behavior more obvious:

  // Extended examples $ Json = '{"0": "a"}'; $ Obj = json_decode ($ json); $ A = (array) $ obj; Var_export (one $); Echo ("a0:" a ["0"] "& lt; br & gt;" $); // This row does not work, see the answer $ obj- & gt; {"0"}. "& Lt; br & gt;"; // Works! $ Json = '{"x": "b"}'; $ Obj = json_decode ($ json); $ B = (array) $ obj; Var_export ($ B); Echo ("bx:" $ b ["x"] "& lt; br & gt;" ..); $ C = array ("1" => gt; c); Var_export ($ c); Echo (. "C1:" $ c ["1"] "& lt; br & gt;".); $ D = array ("0" => "D"); Var_export ($ d); Echo ("D0:" $ d ["0"] "& lt; br & gt;".);  

Expanded example output:

  array ('0' => gt; 'a', a0): an array ('x' = & (0 = & gt; 'D', d0: d)  
Div>

There is more information in it. The short version is that the same is observed on PHP objects / classes. A numerical property is invalid on a PHP object, so there is no clear rule that when a object is serializing with another language (jsn / javascript) with a serial key, although you obviously have to do with the above, Anyone with a different prejudice sees the behavior of PHP as a completely legitimate and preferred form in this example.

So, it's like a bug, but it With an answer, there is an undetermined area of ​​the spec, so the behavior is not expected to change to suit your preference, and if it makes the change, it is expected that T-change is permanent.

To address some of the comments, consider it

  header ('content-type: text / plain'); $ Json = '{"0": "a"}'; $ Obj = json_decode ($ json); $ A = (array) $ obj; Var_dump (one $); Var_dump (array (0 = & gt; 'one')); Var_dump (array ('0' = & gt; 'one'));  

Some such output will be

  array (1) {["0"] = & gt; String (1) "a"} array (1) {[0] = & gt; String (1) "a"} array (1) {[0] = & gt; String (1) "a"}  

An array zero with a string key is not a valid PHP build. If you try to create a PHP, then zero will be converted to an intern for you. When you ask PHP to do a cast, there is no definition in it, it ends in forming an array with a string key (because of the ill defined rules about what should be here)

While it is clearly obvious that this part of PHP has "wrong" behavior, which defines the correct behavior in a language that is typed vulnerably, it is not easy.


Comments