首页 > 技术文章 > PHP json_decode为什么将json字符串转成数组是对象格式?

pawn-i 原文

eg.

$a='[{"img":"/uploads/agency/carimgs/5/15515954778091.jpg"},{"img":"/uploads/agency/carimgs/5/15515954774873.jpg"}]';

如果用json_decode($a),得到的是:

array (size=2)
  0 => 
    object(stdClass)[2]
      public 'img' => string '/uploads/agency/carimgs/5/15515954778091.jpg' (length=44)
  1 => 
    object(stdClass)[3]
      public 'img' => string '/uploads/agency/carimgs/5/15515954774873.jpg' (length=44)

可见,返回的结果是 object 而非 array。应以对象形式访问 ->

而对于json_decode这个函数

json_decode() 对JSON数据进行解码,转换为PHP变量
语法:json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
注意:1、$json 为待解码的数据,必须为utf8编码的数据;
   2、$assoc 值为TRUE时返回数组,FALSE时返回对象;
   3、$depth 为递归深度;
   4、$option 二进制掩码,目前只支持 JSON_BIGINT_AS_STRING;
   5、一般只用前面两个参数,如果要数据类型的数据要加一个参数true。

所以json_decode($a,true),就会得到

array (size=2)
  0 => 
    array (size=1)
      'img' => string '/uploads/agency/carimgs/5/15515954778091.jpg' (length=44)
  1 => 
    array (size=1)
      'img' => string '/uploads/agency/carimgs/5/15515954774873.jpg' (length=44)

推荐阅读