如何修改 Laravel 中集合的属性值?

Las*_*loP 4 php laravel

我的收藏:

 ($usersWithCommission) Illuminate\Support\Collection {#2625
  #items: array:2 [
    0 => array:3 [
      "userId" => 1
      "name" => "Sim Aufderhar"
      "net_commission" => null
    ]
    1 => array:3 [
      "userId" => 2
      "name" => "Carolyn Lang III"
      "net_commission" => null
    ]
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想修改 net_commission 属性,但我不能:

foreach ($soldProperties as $property) {
            if (!$property->buyer_user_id && !$property->seller_transferring_user_id) {
                $usersWithCommission->where('userId', $property->user_id)->first()['net_commission'] += $property->net_commission_of_sold;
            }
        }
Run Code Online (Sandbox Code Playgroud)

我怎么能?谢谢你的回答。

小智 5

集合提供了一种方法map,允许您迭代集合并添加/修改字段。

function modify_net_commision($var) {
   return YOUR_LOGIC_HERE;
}

$collection = [
   [ "userId" => 1, "name" => "Sim Aufderhar", "net_commission" => null ],
   [ "userId" => 2, "name" => "Carolyn Lang III", "net_commission" => null ],
];

$external_var = 'I will be used on modify_net_commision function';

$new_collection = collect($collection)->map(function ($arr) use ($external_var) {
    $arr['net_commission'] = modify_net_commision($external_var);
    return $arr;
})
Run Code Online (Sandbox Code Playgroud)

如果您想从集合中删除某些字段,请使用reject方法。

文档: https: //laravel.com/docs/5.8/collections

希望对您有帮助。

祝你有美好的一天。