PHP json_encode - Strange behaviour

萝らか妹 提交于 2019-12-01 07:41:06

问题


Using json_encode to encode an array of dates, it sometimes does one thing, sometimes does another.

For example, if I'm trying to encode something like:

array(6) {
  [0]=>
  string(6) "Jun-24"
  [1]=>
  string(6) "Jun-25"
  [2]=>
  string(6) "Jun-28"
  [3]=>
  string(11) "Training-24"
  [4]=>
  string(6) "Jun-29"
  [5]=>
  string(6) "Jun-30"
}

It will output

["Jun-24","Jun-25","Jun-28","Training-24","Jun-29","Jun-30"]

However, when I try to encode something like:

array(17) {
  [0]=>
  string(6) "Jun-23"
  [1]=>
  string(6) "Jun-24"
  [2]=>
  string(6) "Jun-28"
  [3]=>
  string(11) "Training-24"
  [4]=>
  string(6) "Jun-29"
  [5]=>
  string(6) "Jun-30"
  [6]=>
  string(6) "Jul-06"
  [7]=>
  string(6) "Jul-07"
  [9]=>
  string(6) "Jul-09"
  [10]=>
  string(6) "Jul-16"
  [11]=>
  string(6) "Jul-17"
  [12]=>
  string(6) "Jul-20"
  [13]=>
  string(6) "Jul-23"
  [14]=>
  string(6) "Jul-24"
  [15]=>
  string(6) "Jul-30"
  [16]=>
  string(6) "Aug-01"
  [17]=>
  string(6) "Aug-05"
}

It will output

{"0":"Jun-23","1":"Jun-24","2":"Jun-28","3":"Training-24","4":"Jun-29","5":"Jun-30","6":"Jul-06","7":"Jul-07","9":"Jul-09","10":"Jul-16","11":"Jul-17","12":"Jul-20","13":"Jul-23","14":"Jul-24","15":"Jul-30","16":"Aug-01","17":"Aug-05"}

(Sorry, couldn't find a smaller example where it fails)

Point being, why does it do this? The options are the same, the array is structured the same, what's the issue?


回答1:


Your PHP array is missing entry 8, so is a mapping (object) and not a list (array).




回答2:


You don't have key [8] set in your second example. According to the documentation a sequential array with an unset key will be encoded as a JSON object and not a JSON array.




回答3:


In your first example the array is numbered sequentially from zero. PHP treats this as a conventional array and encodes it accordingly.

In your second example element 8 is missing. PHP treats this as an associative array and encodes the keys accordingly.




回答4:


It is because of the indexing issue, when your index is not proper it will behave like this.

the best way to resolve is reindexing.

$array = array_values($array);

Do like this just before converting to JSON.




回答5:


Just when you encode the array, do this which will reindex array values:

$encoded = json_encode(array_values($myArray));


来源:https://stackoverflow.com/questions/18116987/php-json-encode-strange-behaviour

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!