PHP 对象文本

2022-08-30 09:00:34

在PHP中,我可以很容易地指定数组文本:

array(
    array("name" => "John", "hobby" => "hiking"),
    array("name" => "Jane", "hobby" => "dancing"),
    ...
)

但是,如果我想要对象数组呢?如何在PHP中指定对象文本?即在javascript中,它将是:

[
    {name: "John", hobby: "hiking"},
    {name: "Jane", hobby: "dancing"}
]

答案 1

正如BoltClock所提到的,PHP中没有对象文字,但是您可以通过简单地将数组转换为对象来执行此操作:

$testArray = array(
    (object)array("name" => "John", "hobby" => "hiking"),
    (object)array("name" => "Jane", "hobby" => "dancing")
);

echo "Person 1 Name: ".$testArray[0]->name;
echo "Person 2 Hobby: ".$testArray[1]->hobby;

答案 2

从 PHP 5.4 开始,您还可以使用短数组语法:

$json = [
    (object) ['name' => 'John', 'hobby' => 'hiking'],
    (object) ['name' => 'Jane', 'hobby' => 'dancing'],
];

推荐