在 PHP 中,如何向数组添加对象元素?

phpserver side programmingprogramming更新于 2025/6/27 13:22:17

代码如下 −

示例

$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;

输出

将产生以下输出 −

Suppose myArray already contains ‘a’ and ‘c’, the value of “My name” will be added to it. It becomes
Array {
   a:0, c:1, “My name”:2
}

创建对象后,将其推送到数组末尾(之前已存在)。

替代方案

$myArray[] = (object) ['name' => 'My name'];

相关文章