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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助