PHP json_encode - Strange behaviour

泪湿孤枕 提交于 2019-12-01 09:39:00

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

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.

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.

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.

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

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