如何在Laravel中修改collection的属性值?

时间:2019-05-09 18:50:51

标签: 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
    ]
  ]
}

我想修改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;
            }
        }

我该怎么办? 感谢您的回答。

2 个答案:

答案 0 :(得分:1)

集合提供一种方法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;
})

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

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

希望它对您有帮助。

祝你有美好的一天。

答案 1 :(得分:0)

public function test()
{
    $collection = [
        [ "userId" => 1, "name" => "Sim Aufderhar", "net_commission" => null ],
        [ "userId" => 2, "name" => "Carolyn Lang III", "net_commission" => null ],
     ];
      $data= collect($collection)->map(function($collection, $key) {
       $collect = (object)$collection;
       return [
            'userId' => $collect->userId,
            'name' => $collect->name,
            'net_commission' => $this->modify_commision($key)
       ];
   });

  dd($data);
}

public function modify_commision($key) {
    $property = [
        ['userId' => 1 ,'net_commission_of_sold' => 30],
        ['user_id' => 2,'net_commission_of_sold' => 40]
    ];
    return $property[$key]['net_commission_of_sold'];
 }

 ***Hope it helps you***