php json_decode() 如果想要强制生成PHP关联数组,json_decode()需要加一个参数true

时间:2023-03-09 02:18:07
php json_decode() 如果想要强制生成PHP关联数组,json_decode()需要加一个参数true

php json_decode()
该函数用于将json文本转换为相应的PHP数据结构。下面是一个例子:
$json = '{"foo": 12345}';
$obj = json_decode($json);
print $obj->{'foo'}; // 12345

通常情况下,json_decode()总是返回一个PHP对象,而不是数组。比如:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
结果就是生成一个PHP对象:
object(stdClass)#1 (5) {
  ["a"] => int(1)
  ["b"] => int(2)
  ["c"] => int(3)
  ["d"] => int(4)
  ["e"] => int(5)
}

如果想要强制生成PHP关联数组,json_decode()需要加一个参数true:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 
var_dump(json_decode($json,true));
结果就生成了一个关联数组:
array(5) {
  ["a"] => int(1)
  ["b"] => int(2)
  ["c"] => int(3)
  ["d"] => int(4)
  ["e"] => int(5)
}