PHP - 对象数组

PHP - array of objects

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

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

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

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

$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 中使用它,那么只需构建一个数组即可。带有字符串键的数组在编码时将是对象。

您的示例似乎是格式正确的 JS array/object 声明:

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"
    ]
];

这不是真正的 "true" 对象,因为只有属性。 这种结构最好作为简单的数组来处理,你的 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 的真参数将强制输出为关联数组。那么您的 $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"
    }
}