php 如何在集合 Laravel 中添加新值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40171556/
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
How to add new value in collection laravel?
提问by MisterPi
I have the following loop where I try to add a new value:
我有以下循环,我尝试添加新值:
foreach ($pro->sig()->get() as $key => $sig) {
$sig->val = 2;
}
When I print the output of $pro->sig()
I don't have the new value $sig->val
当我打印输出时,$pro->sig()
我没有新值$sig->val
回答by Christian Giupponi
If you have a collection you can use push
or put
method.
如果你有一个集合,你可以使用push
或put
方法。
Example with put:
放置示例:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->put('test', 'test');
$collection->all();
The output will be:
输出将是:
['product_id' => 1, 'name' => 'Desk', 'test' => 'test']
Example with push:
推送示例:
$collection = collect([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
Output:
输出:
[1, 2, 3, 4, 5]
Reference: https://laravel.com/docs/5.3/collections#method-push
参考:https: //laravel.com/docs/5.3/collections#method-push
updateReference for 5.8: https://laravel.com/docs/5.8/collections#method-push
5.8 的更新参考:https: //laravel.com/docs/5.8/collections#method-push
回答by suguna
In my example, I tried like the below
在我的例子中,我尝试如下
foreach ($user->emails as $key => $email) {
$email->test = "test";
}
return $user->emails;
It outputs like,
它输出像,
{
"id": 76,
"user_id": 5,
"additional_email": "[email protected]",
"test": "test"
}
Please try like this.
请尝试这样。