PHP json_decode:对象到关联数组
json_decode 的语法是:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
注意第二个参数 $assoc
,它是可选的,默认为 false。 当此参数为 true
时,json_decode
会将对象转换为关联数组。
我的问题是: 是否存在您不想要将返回的对象转换为关联数组的情况?
The syntax for json_decode is:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
Note the 2nd parameter $assoc
which is optional and defaults to false.
When this parameter is true
, json_decode
converts objects to associative arrays.
My question is:
Is there every a case where you would NOT want to convert a returned object into an associative array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果函数返回关联数组,则在 PHP 5.4 之前,您无法直接通过 foo()['xxx'] 访问其成员。但是,如果它返回一个对象,您可以通过 foo()->xxx 访问成员。
当然,您可能还有需要您将返回值作为对象访问的库。
If a function returns an associative array, prior to PHP 5.4 you couldn't access its members directly as foo()['xxx']. However if it returns an object you can access the members as foo()->xxx.
Of course you may also have libraries that require you to access the return value as an object.
当你想将其转换为对象时......
When you want it converted to an object...
就我个人而言,我总是要求一个关联数组,并且发现它比 $assoc=false 时返回的对象更容易使用。
但我想说的是,我见过的大多数其他人的代码(主要是各种 Web 服务客户端库)都使用了 json_decode 和 $assoc=false 以及对象而不是关联数组。我认为这主要是一个偏好问题,因为我没有看到选择其中一种方式的任何特别强有力的理由。
抱歉没有回答:-)
Personally I always ask for an associative array and find it easier to work with than the object returned when $assoc=false.
But I would say the majority of other people's code I've seen (largely various web service client libraries) has used json_decode with $assoc=false and objects instead of associative arrays. I think it's mostly a matter of preference though, as I've not seen any particular strong reason for choosing one way or the other.
Sorry for the non-answer :-)
在我看来,这是一种强调列表(在 php 中由数字数组表示)和实体(对象)之间差异的方法。这可能更具可读性,因为可以通过使用的访问器(
[]
或->
)读取访问的数据类型。In my oppinion its a way to accentuate the difference between a list (in php expressed by a numeric array) and an entity (the object). This could be more readable, because one can read be the used accessor (
[]
or->
) what kind of data is accessed.您需要传递一个具有真实值的额外参数。
json_decode($p,true);
You need to pass an extra argument with true value.
json_decode($p,true);