Я пришел из фона JavaScript, я хочу сделать что-то похожее на это.
$questions = [
{
"title" => "this is the title",
"description" => "this is the desctiption"},
{
"title" => "this is the title2",
"description" => "this is the desctiption2"}
];
Как мне создать массив объектов в PHP?
Ваш пример выглядит как правильно сформированное объявление массива / объекта 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"]
];
Самый быстрый способ для стандартного объекта — создать массивы и привести их к объекту:
$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 может быть легко преобразована в массив, подобный этому:
$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"}
}