dongqichang7988
2014-05-23 03:05
浏览 355

PHP json_decode()是否总是保留JSON数组的数组顺序?

Does the string

 ["first","second","third"]

always preserve array order and result in the PHP array

array('first','second','third');

when using json_decode()? I realize the answer is NO for objects, but I am asking about a string representing an array as input.

图片转代码服务由CSDN问答提供 功能建议

字符串

  [“first”,“second  “,”第三个“] 
   
 
 

始终保留数组顺序并生成PHP数组

 数组(' 第一个','秒','第三个'); 
   
 
 

使用 json_decode()时? 我意识到答案是对象没有,但我问的是一个表示数组的字符串作为输入。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyunqin7307 2014-05-23 03:10
    已采纳

    Yes. Arrays are ordered by definition, and JSON preserves this.

    The JSON specification says:

    An array structure is a pair of square bracket tokens surrounding zero or more values. The values are separated by commas. The order of the values is significant.

    The last sentence implies that a JSON encoder or decoder that changes the order is not in conformance with the specification. I can't find anything in the PHP documentation that explicitly says that it observes this requirement, but I think it can be assumed since it claims to be implementing JSON.

    已采纳该答案
    打赏 评论
  • dongmubei7950 2014-05-23 03:11

    Yes order will be kept.

    Alternatively you can use cast array to object, as order of object variables are not modified json_encode((object)$arr).

    打赏 评论

相关推荐 更多相似问题