使用 json_decode
根据 PHP 文档,有必要表明我们是否希望从 json_decode 获取关联数组而不是对象,代码如下所示:
json_decode($jsondata, true);
使用 json_decode 的 assoc 参数
在 json_decode 函数中,有一个称为 assoc 的参数。
它旨在将返回的对象转换为关联数组。
这是它的样子:
mixed json_decode ( string $json [, bool $assoc = FALSE ] )
但是,请注意,由于 assoc 参数设置为 FALSE,因此有必要将其设置为 TRUE 以检索数组。
这是另一个例子:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true));
上面代码的输出是:
object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) } array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }
关于 PHP 中的 json_decode
json_decode 函数用于获取 JSON 编码的字符串并将其转换为 PHP 变量。
它有四个参数:json、assoc、depth 和 options。
一旦 assoc 参数为 TRUE,则返回的对象将被转换为关联数组。
json_encode 函数能够以适当的 PHP 类型返回以 JSON 编码的值。
有时,在尝试将 JSON 解码为数组时,会遇到错误。
日期:2020-06-02 22:15:50 来源:oir作者:oir