在 PHP 中,如何将对象元素添加到数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14572313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In PHP, how can I add an object element to an array?
提问by adamdport
I'm using PHP. I have an array of objects, and would like to add an object to the end of it.
我正在使用 PHP。我有一个对象数组,并想在它的末尾添加一个对象。
$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?
以上是功能性的,但是有没有一种更清晰、更易读的方式来编写它?也许是一行?
回答by halfer
Just do:
做就是了:
$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;
You need to create the object first (the newline) and then push it onto the end of the array (the []line).
您需要先创建对象(new行),然后将其推到数组的末尾([]行)。
You can also do this:
你也可以这样做:
$myArray[] = (object) ['name' => 'My name'];
However I would argue that's not as readable, even if it is more succinct.
但是,我认为这不是那么可读,即使它更简洁。
回答by Frederik Kammer
Do you really need an object? What about:
你真的需要一个对象吗?关于什么:
$myArray[] = array("name" => "my name");
Just use a two-dimensional array.
只需使用二维数组。
Output (var_dump):
输出(var_dump):
array(1) {
[0]=>
array(1) {
["name"]=>
string(7) "my name"
}
}
You could access your last entry like this:
您可以像这样访问您的最后一个条目:
echo $myArray[count($myArray) - 1]["name"];
回答by ahinkle
Here is another clean method I've discovered if you have multiple records within a foreach:
这是我发现的另一种干净的方法,如果您在一个 中有多个记录foreach:
$foo = [];
array_push($foo, (object)[
'key1' => 'fooValue'
'key2' => 'fooValue2'
'key3' => 'fooValue3'
]);
return $foo;
回答by Moisés Márquez
Something like:
就像是:
class TestClass {
private $var1;
private $var2;
private function TestClass($var1, $var2){
$this->var1 = $var1;
$this->var2 = $var2;
}
public static function create($var1, $var2){
if (is_numeric($var1)){
return new TestClass($var1, $var2);
}
else return NULL;
}
}
$myArray = array();
$myArray[] = TestClass::create(15, "asdf");
$myArray[] = TestClass::create(20, "asdfa");
$myArray[] = TestClass::create("a", "abcd");
print_r($myArray);
$myArray = array_filter($myArray, function($e){ return !is_null($e);});
print_r($myArray);
I think that there are situations where this constructions are preferable to arrays. You can move all the checking logic to the class.
我认为在某些情况下,这种结构比数组更可取。您可以将所有检查逻辑移动到类中。
Here, before the call to array_filter $myArrayhas 3 elements. Two correct objects and a NULL. After the call, only the 2 correct elements persist.
在这里,在调用 array_filter 之前$myArray有 3 个元素。两个正确的对象和一个 NULL。调用后,只有 2 个正确的元素仍然存在。

