doushi1847 2018-12-13 18: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!

$data = SomeModel::get();
for($i = 1; $i <= $max; $i++) {
  $random = $data->random($numberToPick);
  foreach($random as $option) {
    $data->forget($option->id);
  }
}

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 21: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:

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作