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

时间:2010-02-17 15:35:31

标签: php json

观察这个小脚本:

$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_encoded然后json_decoded的数组不应该产生完全相同的结果吗?

7 个答案:

答案 0 :(得分:137)

仔细查看https://secure.php.net/json_decode

json_decode($json, $assoc, $depth)的第二个参数

答案 1 :(得分:73)

$arrayDecoded = json_decode($arrayEncoded, true);

给你一个数组。

答案 2 :(得分:15)

回答实际问题:

  

为什么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"]}

JSON格式源自与JavaScript( ECMAScript编程语言标准)相同的标准,如果您看一下它看起来像JavaScript的格式。它是一个JSON 对象 {} =对象),具有属性&#34; stuff&#34;有价值的&#34;东西&#34;并有一个属性&#34;东西&#34;它的值是一个字符串数组( [] = array )。

JSON(作为JavaScript)并不知道关联数组只能索引数组。因此,当JSON编码PHP关联数组时,这将导致包含此数组的JSON字符串为&# 34;对象&#34;

现在我们使用json_decode($arrayEncoded)再次解码JSON。解码函数不知道这个JSON字符串的来源(PHP数组),所以它解码成一个未知对象,在PHP中是stdClass。正如您将看到的,&#34;事物&#34;字符串数组将解码为索引的PHP数组。

另见:

感谢https://www.randomlists.com/things对于&#39;

答案 3 :(得分:4)

尽管如上所述,您可以在此处添加第二个参数,以指示您想要返回一个数组:

$array = json_decode($json, true);

许多人可能更喜欢投射结果:

$array = (array)json_decode($json);

阅读可能会更清楚。

答案 4 :(得分:2)

tl; dr:JavaScript不支持关联数组,因此JSON也不支持。

毕竟,它是JSON,而不是JSAAN。 :)

因此,PHP必须将您的数组转换为对象才能编码为JSON。

答案 5 :(得分:0)

在这篇博文中写了一篇很好的PHP 4 json编码/解码库(甚至是PHP 5反向兼容):Using json_encode() and json_decode() in PHP4 (Jun 2009)

具体代码由Michal Migurski和Matt Knapp撰写:

答案 6 :(得分:0)

    var_dump(json_decode('{"0":0}'));    // output: object(0=>0)
    var_dump(json_decode('[0]'));          //output: [0]

    var_dump(json_decode('{"0":0}', true));//output: [0]
    var_dump(json_decode('[0]', true));    //output: [0]

如果将json解码为数组,在这种情况下信息将会丢失。

相关问题