在 PHP 中,如何将对象元素添加到数组中? [英] In PHP, how can I add an object element to an array?

查看:77
本文介绍了在 PHP 中,如何将对象元素添加到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHP.我有一个对象数组,想在它的末尾添加一个对象.

I'm using PHP. I have an array of objects, and would like to add an object to the end of it.

$myArray[] = null; //adds an element
$myArray[count($myArray) - 1]->name = "my name"; //modifies the element I just added

以上是功能性的,但有没有更清晰、更易读的方式来编写它?也许只有一行?

The above is functional, but is there a cleaner and more-readable way to write that? Maybe one line?

推荐答案

只需:

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

您需要先创建对象(new 行),然后将其推送到数组的末尾([] 行).

You need to create the object first (the new line) and then push it onto the end of the array (the [] line).

您也可以这样做:

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

但是我认为这不是那么可读,即使它更简洁.

However I would argue that's not as readable, even if it is more succinct.

这篇关于在 PHP 中,如何将对象元素添加到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆