开发者

PHP json_decode: Object to Associative Array

开发者 https://www.devze.com 2023-03-05 16:18 出处:网络
The syntax for json_decode is: mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

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?


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...


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 :-)


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.


You need to pass an extra argument with true value. json_decode($p,true);

0

精彩评论

暂无评论...
验证码 换一张
取 消