观察这个小脚本:
$array = array('stuff' => 'things');
print_r($array);
//prints - Array ( [stuff] => things )
$arrayEncoded = json_encode($array);
echo $arrayEncoded . "<br />";
//prints - {"stuff":"things"}
$arrayDecoded = json_decode($arrayEncoded);
print_r($arrayDecoded);
//prints - stdClass Object ( [stuff] => things )
Run Code Online (Sandbox Code Playgroud)
为什么PHP将JSON对象转换为类?
如果不是一个数组,它是json_encoded那么json_decoded产生完全相同的结果?
Vol*_*erK 141
采取在的第二个参数仔细看看json_decode($json, $assoc, $depth)在https://secure.php.net/json_decode
Kai*_*han 76
$arrayDecoded = json_decode($arrayEncoded, true);
Run Code Online (Sandbox Code Playgroud)
给你一个数组.
7oc*_*hem 17
为什么PHP将JSON对象转换为类?
仔细看看编码的JSON的输出,我已经扩展了OP给出的一些例子:
$array = array(
'stuff' => 'things',
'things' => array(
'controller', 'playing card', 'newspaper', 'sand paper', 'monitor', 'tree'
)
);
$arrayEncoded = json_encode($array);
echo $arrayEncoded;
//prints - {"stuff":"things","things":["controller","playing card","newspaper","sand paper","monitor","tree"]}
Run Code Online (Sandbox Code Playgroud)
JSON格式源自与JavaScript(ECMAScript编程语言标准)相同的标准,如果您看一下它看起来像JavaScript的格式.它是一个JSON 对象({}=对象),具有值为"stuff"的属性"stuff",并且具有属性"things",其值为字符串[]数组(= array).
JSON(作为JavaScript)不知道关联数组只有索引数组.因此,当JSON编码PHP关联数组时,这将导致包含此数组的JSON字符串作为"对象".
现在我们再次使用解码JSON json_decode($arrayEncoded).解码函数不知道这个JSON字符串的来源(PHP数组),因此它正在解码为stdClassPHP中的未知对象.正如您将看到的,"things"字符串数组将解码为索引的PHP数组.
另见:
感谢https://www.randomlists.com/things为'事物'
尽管如上所述,您可以在此处添加第二个参数以指示您希望返回一个数组:
$array = json_decode($json, true);
Run Code Online (Sandbox Code Playgroud)
许多人可能更喜欢转换结果:
$array = (array)json_decode($json);
Run Code Online (Sandbox Code Playgroud)
读起来可能更清楚。
| 归档时间: |
|
| 查看次数: |
92079 次 |
| 最近记录: |