[英]PHP json_encode issue
我有一堆值和一个PHP数组,我需要将其转换为JSON值,以便通过CURL发布到parse.com
问题是PHP数组转换为JSON对象(字符串作为键和值,而字符串作为值)
我最终
{"showtime":{"Parkne":"1348109940"}}
而不是
{"showtime":{Parkne:"1348109940"}}
并且parse抱怨这是一个对象而不是数组,因此不会接受它。
如
{"showtime":{"Parkne":"1348109940"}}
是JSON对象( key = a string
)
反正有使用json_encode
做到这一点吗? 还是一些解决方案?
这就是JSON规范:必须引用对象键。 虽然第一个未引用的版本是有效的Javascript,但引用的版本也是有效的,并且两者在任何Javascript引擎中都将进行相同的解析。 但是在JSON中,必须引用密钥。 http://json.org
跟进:
除非上面的示例是您的数组,否则请说明如何定义数组。 一切都取决于如何定义要编码的PHP结构。
// plain array with implicit numeric keying
php > $arr = array('hello', 'there');
php > echo json_encode($arr);
["hello","there"] <--- array
// array with string keys, aka 'object' in json/javascript
php > $arr2 = array('hello' => 'there');
php > echo json_encode($arr2);
{"hello":"there"} <-- object
// array with explicit numeric keying
php > $arr3 = array(0 => 'hello', 1 => 'there');
php > echo json_encode($arr3);
["hello","there"] <-- array
// array with mixed implicit/explicit numeric keying
php > $arr4 = array('hello', 1 => 'there');
php > echo json_encode($arr4);
["hello","there"] <-- array
// array with mixed numeric/string keying
php > $arr5 = array('hello' => 'there', 1 => 'foo');
php > echo json_encode($arr5);
{"hello":"there","1":"foo"} <--object
盲注...我给您的印象是您的PHP数据结构不是您想开始的。 你可能有这个:
$data = array(
'showtime' => array(
'Parkne' => '1348109940'
)
);
...并且实际上需要这个:
$data = array(
array(
'showtime' => array(
'Parkne' => '1348109940'
)
)
);
随时编辑问题并提供预期输出的样本。
您可以使用json_encode将数组转换为JSON,前提是您的数组不为空,您可以这样做
$array=();
$json = json_encode($array);
echo $json;
听起来您需要将单个对象包装到数组中。
尝试这个:
// Generate this however you normally would
$vals = array('showtime' => array("Parkne" => "1348109940"));
$o = array(); // Wrap it up ...
$o[] = $vals; // ... in a regular array
$post_me = json_encode($o);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.