php Laravel map():如何改变对象和数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34807863/
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
Laravel map(): How to alter objects and arrays?
提问by MikaelL
I have a multidimensional collection. I want to iterate it and alter some of its child objects and arrays using the map() function: https://laravel.com/docs/5.1/collections#method-map
我有一个多维集合。我想迭代它并使用 map() 函数更改它的一些子对象和数组:https: //laravel.com/docs/5.1/collections#method-map
Sample content:
示例内容:
[
{
'address': 'Somestreet 99'
'orders': [
{'id': 11},
{'id': 67}
]
}
]
Example
例子
$deliveries = $delivery_addresses->map(function($delivery_address){
$orders = $delivery_address->orders->filter(function($order){
return $order->id == 67;
});
$delivery_address['address'] = 'A different street 44'
$delivery_address['orders'] = $orders;
$delivery_address['a_new_attribute'] = 'Some data...';
return $delivery_address;
});
Expected result:
预期结果:
[
{
'address': 'A different street 44'
'orders': [
{'id': 67}
],
'a_new_attribute': 'Some data...;
}
]
The result is that only string type variables will be changed. Any arrays or objects will stay the same. Why is this and how to get around it? Thanks! =)
结果是只会更改字符串类型变量。任何数组或对象都将保持不变。为什么会这样以及如何解决它?谢谢!=)
回答by Mayuri Pansuriya
collect($deliver_addresses)->map(function ($address) use ($input) {
$address['id'] = $input['id'];
$address['a_new_attribute'] = $input['a_new_attribute'];
return $address;
});
回答by Sturm
Addressing your recent edits, try this:
解决您最近的编辑,试试这个:
$deliveries = $deliver_addresses->map(function($da) {
$orders = $da->orders->filter(function($order) {
return $order->id == 67;
});
$da->unused_attribute = $orders->all();
return $da;
});
What the case most likely is here is that you are correctly overwriting that attribute. Then when you are attempting to access it Laravel is querying the orders() relationship and undoing your changes. As far as Laravel is concerned these are the same:
这里最有可能的情况是您正确地覆盖了该属性。然后,当您尝试访问它时,Laravel 会查询 orders() 关系并撤消您的更改。就 Laravel 而言,这些是相同的:
$delivery_address->orders;
$delivery_address['orders'];
This is why the changes are only working on objects. If you want to save that permanently then actually save it, if not use a temporary attribute to contain that data.
这就是更改仅适用于对象的原因。如果您想永久保存,则实际保存它,如果不使用临时属性来包含该数据。
回答by Carlos Cuamatzin
$paymentMethods = $user->paymentMethods()->map(function($paymentMethod){
return $paymentMethod->asStripePaymentMethod();
});