【问题标题】:PHP - array of objectsPHP - 对象数组
【发布时间】:2018-11-08 09:43:10
【问题描述】:

我来自javascript背景,我想做类似的事情。

$questions = [
      {
       "title" => "this is the title",
       "description" => "this is the desctiption"
      },
      {
       "title" => "this is the title2",
       "description" => "this is the desctiption2"
      }
    ];

如何在 PHP 中创建对象数组?

【问题讨论】:

  • 我认为associative arrays 可能是最好的起点,但如果你想要真正的 PHP 对象,那么你将不得不研究stdClass()
  • 创建对象并放入数组?顺便说一句,你想做什么?基本上,以你的例子,在构造函数中创建一个具有你的属性的类,在数组中直接实例化它们
  • 基本上,把那些花括号{改成方括号[

标签: php arrays object arrayobject


【解决方案1】:

使用标准对象的最快方法是创建数组并强制转换为对象:

$questions = [
      (object)[
       "title" => "this is the title",
       "description" => "this is the desctiption"
      ],
      (object)[
       "title" => "this is the title2",
       "description" => "this is the desctiption2"
      ]
];

或者您可以对数组进行 JSON 编码和解码:

$questions = [
      [
       "title" => "this is the title",
       "description" => "this is the desctiption"
      ],
      [
       "title" => "this is the title2",
       "description" => "this is the desctiption2"
      ]
];

$questions = json_decode(json_encode($questions));

如果您这样做是为了在 JSON 中使用它,那么只需构建一个数组。带有字符串键的数组在编码时将是对象。

【讨论】:

    【解决方案2】:

    您的示例似乎是格式正确的 JS 数组/对象声明:

    var questions = [
      {
       "title" => "this is the title",
       "description" => "this is the desctiption"
      },
      {
       "title" => "this is the title2",
       "description" => "this is the desctiption2"
      }
    ];
    

    所以在 PHP 中实现类似结果的最简单方法是:

    $questions = [
        [
            "title" => "this is the title",
            "description" => "this is the desctiption"
        ],
        [
            "title" => "this is the title2",
            "description" => "this is the desctiption2"
        ]
    ];
    

    【讨论】:

    • 这是一个数组,不是对象。
    • @AbraCadaver 你是对的,希望我的更新能纠正任何误解。
    【解决方案3】:

    这不是真正的“真实”对象,因为只有属性。 这种结构最好作为简单的数组来处理,你的 JS 字符串可以很容易地转换成这样的数组:

    $questions = '[
        {
        "title" => "this is the title",
        "description" => "this is the desctiption"
        },
        {
        "title" => "this is the title2",
        "description" => "this is the desctiption2"
        }
    ]';
    
    $my_array = json_decode($questions, true);
    

    请注意, json_decode 的 true 参数将强制输出为关联数组。那么你的 $my_array 将是:

    array(2)
    {
        [0]=>
        array(2) {
            ["title"]=>
            string(17) "this is the title"
            ["description"]=>
            string(23) "this is the desctiption"
        }
        [1]=>
        array(2) {
            ["title"]=>
            string(18) "this is the title2"
            ["description"]=>
            string(24) "this is the desctiption2"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-26
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      • 2021-04-14
      相关资源
      最近更新 更多