将 json_decode 转换为对象

Converting json_decode to an object

我使用 json_decode

得到以下输出
Array
(
    [0] => Array
        (
            [...] => ...
            [...] => ...
        )

    [1] => Array
        (
            [...] => ...
            [...] => ...
        )

我想做的是将其导入 class,这样我就可以从内存中调用和引用数据。

我通过研究发现: How to convert an array into an object using stdClass()

但是,我不确定 stdClass 是否是我想要的方式?

将对象放在数组开始之前

$arr = Array([0] => Array
    (
        [...] => ...
        [...] => ...
    )[1] => Array
    (
        [...] => ...
        [...] => ...
    ));

 $arr = (object) $arr;

来自 PHP manual 的函数定义:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

考虑到您的 JSON 字符串 [{"first_name":"Jason","last_name":"Pass", [...],您必须使用 json_decode 并将其第二个参数设置为 TRUE。

这意味着 JSON 字符串中的对象作为关联数组返回。如果省略第二个参数(或使用默认的 FALSE 值),您将得到:

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'first_name' => string 'Jason' (length=5)
      public 'last_name' => string 'Pass' (length=4)
      ...
  1 => 
    object(stdClass)[2]
      ...

这意味着来自 JSON 字符串的对象被保留为对象。

但是,包含您的对象的数组将仍然是一个数组,因为它应该是这样的,您不应该强迫它成为一个对象。没有充分的理由这样做。