doushi1847 2018-12-13 10:54
浏览 17
已采纳

忘记不修改原始集合Laravel 5.7

I'm attempting to to remove random elements from a collection while iterating through a for loop. The idea is that each time it goes through the for loop, the items in the collection available doesn't include items found and removed in previous iterations. I've attempted to use forget on the initial collection, but i'm still finding doubles in the results. Any help would be appreciated, thanks!

  1. $data = SomeModel::get();
  2. for($i = 1; $i <= $max; $i++) {
  3. $random = $data->random($numberToPick);
  4. foreach($random as $option) {
  5. $data->forget($option->id);
  6. }
  7. }

I dd($data) at the end, and do indeed see the items selected are removed from the final collection, but as mentioned, i'm still getting some randoms that have keys matching previous iterations.

  • 写回答

1条回答 默认 最新

  • download1323 2018-12-13 13:14
    关注

    The problem here is that forget will remove the item by its index. You are giving as argument the id of the object inside the collection, but its index is not the same as the id.

    Try this:

    1. $data = SomeModel::get()->keyBy('id');
    2. for($i = 1; $i <= $max; $i++) {
    3. $random = $data->random($numberToPick);
    4. foreach($random as $option) {
    5. $data->forget($option->id);
    6. }
    7. }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部