我有一个多维集合。我想迭代它并使用map()函数改变它的一些子对象和数组:https://laravel.com/docs/5.1/collections#method-map
示例内容:
[
{
'address': 'Somestreet 99'
'orders': [
{'id': 11},
{'id': 67}
]
}
]
实施例
$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;
});
预期结果:
[
{
'address': 'A different street 44'
'orders': [
{'id': 67}
],
'a_new_attribute': 'Some data...;
}
]
结果是只会更改字符串类型变量。任何数组或对象都将保持不变。这是为什么以及如何绕过它?谢谢! =)
答案 0 :(得分:9)
collect($deliver_addresses)->map(function ($address) use ($input) {
$address['id'] = $input['id'];
$address['a_new_attribute'] = $input['a_new_attribute'];
return $address;
});
答案 1 :(得分:5)
解决您最近的修改,请尝试以下方法:
$deliveries = $deliver_addresses->map(function($da) {
$orders = $da->orders->filter(function($order) {
return $order->id == 67;
});
$da->unused_attribute = $orders->all();
return $da;
});
最有可能的情况是您正确覆盖该属性。然后,当您尝试访问它时,Laravel正在查询orders()关系并撤消您的更改。就Laravel而言,这些是相同的:
$delivery_address->orders;
$delivery_address['orders'];
这就是为什么更改仅适用于对象。如果你想永久保存它,那么实际保存它,如果不使用临时属性来包含那些数据。
答案 2 :(得分:1)
$paymentMethods = $user->paymentMethods()->map(function($paymentMethod){
return $paymentMethod->asStripePaymentMethod();
});