PHP json_encode问题与数组0键 [英] PHP json_encode issue with array 0 key

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

问题描述

我在使用json_encode从数组生成json编码的字符串时遇到问题.

I am having a problem using json_encode to generate a json encoded string from an array.

有问题的数组部分看起来像这样

The section of the array in question looks like this

RatingDistribution (Array, 11 elements)
    0 (Array, 1 element)
        0 (String, 3 characters ) 4.5
    1 (Array, 1 element)
        1 (String, 4 characters ) 11.9
    2 (Array, 1 element)

但是会在字符串中产生此结果:

But produces this in the string:

"RatingDistribution":[["4.5"],{"1":"11.9"},

我希望这样:

"RatingDistribution":[{"0":"4.5"},{"1":"11.9"},

我正在做的就是这个

$result = json_encode($array);

我做错了什么吗?还是需要更多代码来确保0键存在?

Have I done something wrong or do I need more code to ensure the 0 key is present?

欢呼 安迪

推荐答案

应该得到预期的结果; json_encode检测到您仅在数组中使用数字键,因此它将其转换为数组,而不是JSON中的对象.大多数时候,这正是您想要做的.

The result you are getting should be expected; json_encode detects that you are only using numeric keys in the array, so it translates that to an array instead of an object in JSON. Most of the time, that's exactly what you want to do.

如果出于某种原因(为什么?)不这样做(在PHP> = 5.3中,则可以使用 JSON_FORCE_OBJECT 标志以获取所需的输出:

If for some reason you don't (why?), in PHP >= 5.3 you can use the JSON_FORCE_OBJECT flag to get your desired output:

$result = json_encode($array, JSON_FORCE_OBJECT);

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

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