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

Der*_*air 102 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 )
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

  • 这真的没有回答这个问题,它只是提供了一种解决方法.但是,一个糟糕的解决方法,IMO.如果您希望将json编码的对象解码为对象并将json解码的关联数组自动解码为关联数组,该怎么办?将第二个参数用于json_decode()意味着某种人为干预.坦率地说,这很糟糕(PHP,不是这个答案) (6认同)
  • 不回答问题 - 为什么stdClass是默认值.另请参见/sf/ask/223563581/ (4认同)
  • @JDS我添加了一个答案,该答案实际上回答了“ PHP为什么将JSON对象转换为类?”的问题。 (2认同)

Kai*_*han 76

$arrayDecoded = json_decode($arrayEncoded, true);
Run Code Online (Sandbox Code Playgroud)

给你一个数组.

  • 这真是太糟糕了,谢谢@Kai Chain-我想最初的问题是问“为什么”,但这似乎可以达到他们的预期。无论如何,最适合我的情况。 (2认同)

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为'事物'

  • 这是正确的答案......它回答了问题,而其他答案则为无法解释的问题提供了解决方法。谢谢,我一直在兜圈子,忘记了 JSON 不支持关联数组! (3认同)

And*_*rew 6

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

$array = json_decode($json, true);
Run Code Online (Sandbox Code Playgroud)

许多人可能更喜欢转换结果:

$array = (array)json_decode($json);
Run Code Online (Sandbox Code Playgroud)

读起来可能更清楚。

  • 有不同。请注意您是否编码了多维数组或对象。第一个为您提供数组数组,第二个为您提供对象数组。 (5认同)