json_encode/json_decode - 在 PHP 中返回 stdClass 而不是 Array

2022-08-30 07:11:17

观察这个小脚本:

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

为什么 PHP 将 JSON 对象转换为类?

那么一个数组不应该产生完全相同的结果吗?json_encodedjson_decoded


答案 1

仔细看看 at 的第二个参数 https://secure.php.net/json_decodejson_decode($json, $assoc, $depth)


答案 2
$arrayDecoded = json_decode($arrayEncoded, true);

给你一个数组。


推荐