json_encode() 的问题 [英] Problem with json_encode()

查看:33
本文介绍了json_encode() 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的数组:

array
  0 => string 'Kum' (length=3)
  1 => string 'Kumpel' (length=6)

当我使用 json_encode() 对数组进行编码时,我得到以下信息:

when I encode the array using json_encode(), i get following:

["Kum","Kumpel"] 

我的问题是,得到 ["Kum","Kumpel"] 而不是 { "0" : "Kum", "1" : "Kumpel" 的原因是什么}?

My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?

推荐答案

"{}" 括号指定一个对象,"[]" 用于根据 JSON 规范的数组.如果从内存分配的角度来看,数组没有枚举.它只是数据后跟更多数据,来自其他方面的对象具有带名称的属性,并且数据被分配给属性,因此要对此类对象进行编码,您还必须传递正确的属性名称.但是对于数组,您不需要指定索引,因为它们总是 0..n,其中 n 是数组的长度 - 1,唯一重要的是数据的顺序.

"{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.

$array = array("a","b","c");
json_encode($array); // ["a","b","c"]
json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}

JSON_FORCE_OBJECT 之所以强制使用 "0,1,2" 是因为要将数据分配给对象,您必须将其分配给一个属性,因为开发人员没有给出属性名称(只有数据)编码器使用数组索引作为属性名称,因为这些是唯一有意义的名称.

The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.

注意:根据PHP 手册,选项参数仅适用于 PHP 5.3.

Note: according to PHP manual the options parameters are only available from PHP 5.3.

对于较旧的 PHP 版本,请参阅 chelmertz 的答案,以获取使 json_encode 使用索引的方法.

这篇关于json_encode() 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆